Posted on

Android Next Level Networking w/ RxJava


Android Networking with RxJava  
Designed by Freepik

Hey, guys, today we’re going to improve out networking by using RxJava library. It’s not something new, but there still might be people who not familiar with it. And hopefully after today you will be convinced to switch completely to it. We’ll talk about advantages you get, otherwise why would you consider to switch from AsyncTask/Loader, pure Retrofit. Let’s get started!

Purpose

First of all let’s see the purpose of it. It’s basically a wrapper for you networking which will make it cleaner and safer.  Not all networking needs RxJava. Let’s say we have some simple api calls. If we just make networking, we’re good with just Thread. If we need to update UI after it, we can use ether AsyncTask, where onPostExecute is being run on UI thread or using OkHttp enqueue method which is async, but we can still run result on main thread with runOnUiThread method from Activity.

For simple api calls like that OkHttp seems to be the most beautiful solution. But there’s one downpoint of first two approaches – Android lifecycle.

Android Lifecycle

If you started ether one of first two ones and rotated/started new activity they won’t care about it. There still going to be a call to change UI views. Which can cause null pointers. Solution – RxLifecycle library which cancels networking and there will be no UI change callbacks. Just add extend RxAppCompatActivity and add this line to your chain

Chains

As you see, it’s not that convincing from simple examples. But the real power comes in really complex api callbacks. Which looks really minimalistic with RxJava especially with lambdas. What so ever, do you hate onSuccess nested callbacks, more and more one in another depending on each success? Well, I do.

You might not have dealt with so super complex api chains. Let’s make up a sign up chain and let’s imagine we don’t care about networking optimization, we just make as many call as we can. First we sign up, make call to check if there some of our contacts already signed up. If there are, send friend requests. That’s three networking calls depending on each other’s success state. What does it mean? It means we need to check for success each time, nesting, nesting, nesting callbacks. Annoying!

How do we make it look nice with RxJava? By using map method we can retrieve the value returned from previous call, modify and return new one to the next possible map method. And the best thing, you don’t need to check for success state each time. If it’s in next map method, then it was successful.

Build Up Objects

One more awesome thing about those chains, you can completely change return types. You can start with call returning a string and then build up your api model. Let’s say you have api endpoints which don’t return the whole model fields. With map methods you can build up your full model. Now, of course you can do the same thing even with Thread class, but state check with deep nesting totally killing.

In Chain Stream

One more awesome thing is you can stream through interable right in the chain, using flatMap and Observable.fromIterable. You can filter, basically everything you need to do with the data fetched you can do  in that one chain. Following from the code before to iterate though all signed up friends we would make code look like this

 

 

 

And that’s not even a half of all the possibilities you have with RxJava. Once again, it’s not going to make a difference if you have simple straightforward single api calls with Retrofit. By the way, you can wrap Retrofit with it as well. But when complexity comes, RxJava helps a lot. And don’t forget to use lambdas with ether Jack ‘n’ Jill or third party libraries. Without them it looks way worse with all the override and method names.

 

Alright, thanks for reading, you can find GitHub repo here. Don’t forget to subscribe, follow me on G+, Twitter, Facebook and share with friends if you think they will benefit from it!

 


  • Steel Rat

    Hi Игорь!
    Thanks for good tutorial!
    Now I’m trying to make my own project of few examples and I’m getting NetworkOnMainThreadException
    it’s something with retrofit2…
    .observeOn(Schedulers.io()) is there from the start

    • Thank you! Hm, did you mean you get exception with RxJava 2? If Retrofit, then it’s enqueue() instead of execute()

      • Steel Rat

        As usual when you work on something for few hours – you do stupid mistakes 🙂
        It’s OK now.
        Tnx for asking )

  • Steel Rat

    Hi Игорь!
    I have an interesting task and I would like to ask your advice, if you don’t mind.

    Task is to get some JSON with strings and then load it to RecyclerView.
    One of it’s items is a list of tags.
    And I want to provide an ability to filter items by this tags.

    Obviously, I have to load JSON to get this tags as I don’t know them.
    So I load it, fill up RecyclerView. – Here all RX magic is finished, no need to make another request.
    And then I can provide ability to user to filter.

    Is there a way to create some adorable Observable to implement filtering of already downloaded data,
    like _something_ fromIterable …?
    At this point I think to make a method like FillData(List filter) that will filter and fill it the old fashion way.

    Not sure if I’m missing something or it is the only sane way to do it 🙂