2017-06-21 65 views
0

Rx的新功能,所以在寻找将以下AsyncTask转换为Rx的帮助后,希望能够使用我已经知道的某些代码来可视化Rx。我发现了一些其他的答案,这些答案有点相关,但是它们中的很多不需要网络请求,而且许多人使用不同的操作符来提供不同的答案,所以我有点困惑。将AsyncTask转换为RxJava

继承人的的AsyncTask:

这里是我的WhatsTheWeather应用程序的Java代码(从在MainActivity所有代码都包含):

public class MainActivity extends AppCompatActivity { 

EditText cityName; 
TextView resultTextview; 

public void findTheWeather(View view){ 
    Log.i("cityName", cityName.getText().toString()); 

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
    mgr.hideSoftInputFromWindow(cityName.getWindowToken(), 0); 

    try { 
     String encodedCityName = URLEncoder.encode(cityName.getText().toString(), "UTF-8"); 
     DownLoadTask task = new DownLoadTask(); 
     task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=a018fc93d922df2c6ae89882e744e32b"); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
     Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show(); 
    } 
} 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    cityName = (EditText)findViewById(R.id.cityName); 
    resultTextview = (TextView) findViewById(R.id.resultTextView); 

} 


public class DownLoadTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     String result = ""; 
     URL url; 
     HttpURLConnection urlConnection = null; 
     try { 
      url = new URL(urls[0]); 
      urlConnection = (HttpURLConnection)url.openConnection(); 

      InputStream inputStream = urlConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(inputStream); 

      int data = reader.read(); 
      while(data != -1){ 
       char current = (char) data; 
       result +=current; 
       data = reader.read(); 
      } 
      return result; 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 
      String message = ""; 
      JSONObject jsonObject = new JSONObject(result); 

      String weatherInfo = jsonObject.getString("weather"); 
      Log.i("Weather content", weatherInfo); 
      JSONArray arr = new JSONArray(weatherInfo); 

      for(int i=0; i<arr.length(); i++){ 
       JSONObject jsonPart = arr.getJSONObject(i); 

       String main = ""; 
       String description=""; 

       main = jsonPart.getString("main"); 
       description = jsonPart.getString("description"); 

       if(main != "" && description != ""){ 
        message += main + ": "+ description + "\r\n"; //for a line break 
       } 

      } 

      if (message != ""){ 
       resultTextview.setText(message); 
      } else { 
       Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show(); 
      } 
     } catch (JSONException e) { 
      Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show(); 
     } 
    } 
} 
+0

你到目前为止尝试过什么? –

+0

如果代码块组织在一起,您的问题会更容易阅读,并且您的实际问题不会分解为块引用。 [Markdown帮助](https://stackoverflow.com/editing-help)文档演示了如何执行此操作。 – jeffbyrnes

回答

0

有几件事情你在整合Retrofit之前应该知道。

  • 尽量不要使用Retrofit
  • Retrofit2旧版本是你应该在当前
  • 使用尽量避免与目前的(太复杂RxJavaRxAndroidRetrofit代码集成了一个对于初学者)
  • 确保您也熟悉GSONJackson
  • HttpClient折旧而OkHttp相对快于HttpUrlConnection通常使用由Retrofit2
  • 最后,这里的link为Retrofit2。它非常详细且易于理解。杰克沃顿尽力使其尽可能简单易懂。
+0

谢谢!这有助于。 –

+1

HttpUrlConnection不被弃用... –

+0

感谢评论@ crickrt_007。我做了一些编辑。 –

0

试试这个。

public void networkCall(final String urls) { 
    Observable.fromCallable(new Func0<String>() { 
     @Override 
     public String call() { 
      String result = ""; 
      URL url = null; 
      HttpURLConnection urlConnection = null; 
      try { 
       url = new URL(urls); 
       urlConnection = (HttpURLConnection) url.openConnection(); 

       InputStream inputStream = urlConnection.getInputStream(); 
       InputStreamReader reader = new InputStreamReader(inputStream); 

       int data = reader.read(); 

       while (data != -1) { 
        char current = (char) data; 
        result += current; 
        data = reader.read(); 
       } 

       try { 
        String message = ""; 
        JSONObject jsonObject = new JSONObject(result); 

        String weatherInfo = jsonObject.getString("weather"); 
        Log.i("Weather content", weatherInfo); 
        JSONArray arr = new JSONArray(weatherInfo); 

        for (int i = 0; i < arr.length(); i++) { 
         JSONObject jsonPart = arr.getJSONObject(i); 

         String main = ""; 
         String description = ""; 

         main = jsonPart.getString("main"); 
         description = jsonPart.getString("description"); 

         if (main != "" && description != "") { 
          message += main + ": " + description + "\r\n"; //for a line break 
         } 

        } 

        return message; 

       } catch (JSONException e) { 
        Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 
       } 


      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 
    }) 
    .subscribeOn(Schedulers.io()) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .subscribe(new Subscriber<String>() { 
     @Override 
     public void onCompleted() { 

     } 

     @Override 
     public void onError(Throwable e) { 

     } 

     @Override 
     public void onNext(String message) { 
      if (message != ""){ 
       resultTextview.setText(message); 
      } else { 
       Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show(); 
      } 
     } 
    }); 
} 

但是,我建议一起使用Retrofit和RxJava。

相关问题