Luke
Luke

Reputation: 145

Convert AsyncTask to RxJava

Bit new to Rx, so am looking for some help on converting the following AsyncTask to Rx, hopefully so I can visualize Rx a bit more with code that I already know that does something. I've found a few other SO answers that were somewhat relevant, but alot of them werent network requests and many used different operators for different answers, so am a bit confused.

Heres the AsyncTask:

Here is my Java code for an WhatsTheWeather App(all code from the MainActivity is included):

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();
        }
    }
}

Upvotes: 0

Views: 1574

Answers (2)

Ait Bri
Ait Bri

Reputation: 587

There are couple of things you should know before integrating Retrofit.

  • Try not to use the older version of Retrofit
  • Retrofit2 is the one which you are supposed to use at current
  • Try avoiding code integration of Retrofit with RxJava or RxAndroid at current(Too much complexity for beginner)
  • Make sure you are familiar with GSON or Jackson too.
  • HttpClient is depreciated while OkHttp is comparatively faster than HttpUrlConnection which is generally used by Retrofit2
  • Finally, here the link for the Retrofit2. It is well detailed and easy to understand. Jack Wharton has tried his best to make it simple to understand as possible.

Upvotes: 0

Ritt
Ritt

Reputation: 3349

Try this.

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();
            }
        }
    });
}

But, i would recommend to use Retrofit and RxJava together.

Upvotes: 1

Related Questions