How to convert an AsyncTask to RxJava

Pierce Zaifman
AndroidPub
Published in
1 min readMay 14, 2017

--

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.

If You Enjoyed Reading, Please Click That Little Heart. If You Want To Read More Like This, Follow Me On Medium. Thanks!

Originally published at piercezaifman.com on May 14, 2017.

--

--

Pierce Zaifman
AndroidPub

Freelance Android app developer | I love productivity, creativity, and finding balance | Email me for a quote at pierce@piercezaifman.com