Replace Android AsyncTask with RxJava

Today is the day when we will say goodbye to AsyncTask. It will be replaced by our new friend RxJava which is quite in news now a days. We will be covering how RxJava will do the work of  AsyncTask. This post is included in series of post which will cover RxJava in detail.

But why ?

That ok but why do we need to replace our AsyncTask? Because RxJava is more easier to use and we can add more features and controls without changing anything and by just plugging some functions in between. This will make our life easier and manageable. Also there will be much less code and no subclassing at all.

Lets start coding

First of all you have to add support for RxJava in your gradle file as explained in this tutorial. We are using lambda expression in this tutorial for code clarity, so you should setup that also from our tutorial.

Now we are ready to use RxJava with Lambda expression.

This code will sleep for 5 sec on worker thread(not on main thread) and then simply print the letter count of passed string. There will be a loader which will show rotating animation from start to end of this operation.

We will use RxJava.just() for emitting data. Here string is being emitted by just operator. This can be of any type you want, we have taken string for simplicity. It can be url that will be used to download data.

When we click on button then startAsyncTask is called which will emit string using just operator. Now this string is passed to map operator which basically converts one type to other. Here its converting String to int. Expanded code for this step is below.

So basically all the background processing will take place in this function which is  equivalent to doInBackground() in AsyncTask.

Next comes in subscribeOn(Schedulers.io()) which tells RxJava to do this processing on separate worker thread. So basically you can do anything on separate thread just by add a single function.

observeOn(AndroidSchedulers.mainThread()) is where the beauty of RxJava is fully visible. This tells Rxjava to do final result delivery on Android main thread. So when data is delivered after processing then it will be delivered on main thread.

RxJava uses subscription model where a subscriber subscribe for result. doOnSubscribe(this::onPreExecute) calls onPreExecute() function when subscriber subscribe for data. Simple code without lambdas looks like this.

Finally subscribe to get result. subscribe(this::onPostExecute) In expanded form it looks like this. This will call onPostExecute with result after the background work is done.

Thats all we need to do right now. Please comment for queries.

guru

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *