Using RxJava Instead AsyncTask

Shubham Soni
Code Yoga
Published in
3 min readMar 3, 2018

I know we(Android Developers) all use AsyncTask nearly for every heavy background work, sometimes we replace our AsyncTask with Retrofit or Vollley but have you thought of using RxJava Instead of AsyncTask.

Problems with AsyncTask is:

  • MULTIPLE WEB SERVICE CALLS:To solve this in AsyncTask create an inner AsyncTask subclass in our Activity/Fragment, perform the network operation in the background, and take the result of that operation and update the UI in the main thread.This approach has some issues and limitations:
  • Memory/context leaks are easily created is an inner class and thus holds an implicit reference to the outer class Also, what if we want to chain another long operation after the network call? We’d have to nest two AsyncTasks which can significantly reduce readability.
  • ERROR HANDLING: What happens if something goes wrong? Unfortunately, there’s no out-of-the-box solution for this. And other problem like device rotation, back press handle etc.

Handle Error using RxJava is like this:

webService.doSomething(someData)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> resultText.setText("It worked!"),
e -> handleError(e));

Multiple web services call:

public Observable<List<Weather>> getWeatherForLargeUsCapitals() {
return cityDirectory.getUsCapitals()
.flatMap(cityList -> Observable.from(cityList))
.filter(city -> city.getPopulation() > 500,000)
.flatMap(city -> weatherService.getCurrentWeather(city)) //each runs in parallel
.toSortedList((cw1,cw2) -> cw1.getCityName().compare(cw2.getCityName()));
}

Let’s take a look at how we can use RxJava replacing AsyncTask. It will make a network request to a URL and then return whether or not it was successful.

new AsyncTask<String, Void, Boolean>() {
@Override
protected Boolean doInBackground(String... urls) {
Request request = new Request.Builder()
.url(urls[0])
.build();
try {
Response response = sHttpClient.newCall(request).execute();
return response.isSuccessful();
} catch (IOException e) {
Log.e("Network request", "Failure", e);
}

return false;
}

@Override
protected void onPostExecute(Boolean result) {
//Use result for something
}
};

AsyncTask is Android’s default tool for developers needing to do some background task and updating the UI at the same time. Inside the doInBackground method I make a network request to some given URL, and return the result as a Boolean. Then in onPostExecute I could do something with that result.

Now if I want to remove the AsyncTask and replace it with RxJava , you can write it as:

Observable.fromCallable(() -> {
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = sHttpClient.newCall(request).execute();
return response.isSuccessful();
} catch (IOException e) {
Log.e("Network request", "Failure", e);
}

return false;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((result) -> {
//Use result for something
});

So,there are many ways through which you can achieve this in RxJava.AsyncTask is good but if you want to tackle some of its disadvantages then you can go with Rxjava.Using RxJava in your code provides you with much more flexibility and better grip on processing results.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

Shubham Soni
Code Yoga

Senior Executive @Ketto @Dart @Flutter @Java @Android, Editor @FlutterCommunity @CodeBurst.io, App Developer @Senior @Moderator @FlutterDeveloper