How to convert an AsyncTask to RxJava

Let’s take a look at a sample AsyncTask. It will make a network request to a URL and then return whether or not it was successful. For this example I’m using OkHttp, but that part isn’t important.

If you’ve used an AsyncTask before this code should look familiar. 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 (and Retrolambda), one solution would look like this:

There are many ways you could approach this in RxJava. But essentially all I’m doing is creating an Observable which reports on the result of the network request. I observe the result on the main thread (with RxAndroid) so I could make any UI changes. This is effectively the same as the AsyncTask I created. The main difference is that with an Observable I have much more flexibility in how results are processed.

Pierce Zaifman

Android app developer. Hates wasting time and takes satisfaction in improving efficiency in all aspects of life. Also enjoys helping people solve their problems.

London, Ontario, Canada

Subscribe to Pierce Zaifman

Get the latest posts delivered right to your inbox.

or subscribe via RSS.