Little RxJava snippet for chaining network calls

This will be my first blog post ūüôā¬†It’s a little post that I wrote on my personal blog earlier this year, but since it’s Android related, and it took me quite a bit of time to figure out, I figured it’s worth a post since it could be helpful to other developers who are just diving into RxJava.

In Android development, there are a few techniques that you can employ if you want to make network calls. You could:

  1. Do it in a separate thread so that your application doesn’t hang while it’s making an API call
  2. Utilize a SyncAdapter so that the data syncs in the background while your app is either running or is in the background while other apps run
  3. AsyncTask, which “works” but is difficult to chain additional method calls onto once the data is retrieved from the API call

I’m sure there are more ways (I’ve seen some other ways as well, like setting up service patterns and callbacks manually), but you can also make network requests with RxJava fairly easily if you pair RxJava with the awesome RetroFit library. For those of you who aren’t familiar with RxJava, it’s basically an implementation of the observer pattern on steroids.

The basics of RxJava are relatively simple to grasp. You set an observer, you make a request, and once that request completes, the observer goes, “Ok,¬†that initial request is done, I guess we can¬†take the results of the previous¬†method call and do stuff with it”.

Before we continue further, if you have zero experience with RxJava, Dan Lew has written up an excellent series on the basics of RxJava in this link:

Unfortunately,¬†the blog post doesn’t go beyond¬†chaining more than one method.¬†The app I was working on at the time I was playing around with RxJava required me to chain multiple method calls in a specific order, so rather than explaining how things work, I’ll post the code up first and then explain how things work.

I modified the Java class names and variable names for¬†anonymity purposes, but this snippet of code¬†was to authenticate¬†via¬†the backend API. Some service that I’ve written was¬†instantiated¬†via the factory generator pattern, and then I call the loginUserRx method on it. And then I continuously chain doOnNext and flatMap, both of which are RxJava methods, to “massage” the data that I get back from the API. I then subscribe the¬†method chains ¬†on and observe the whole chain of methods on the main thread.¬†At the end, there are three methods that are overwritten, which consist of onCompleted, onError, and onNext.

I’m by no means an expert in RxJava yet, but the above¬†(along with Dan Lew’s RxJava series) should be sufficient to get you started with RxJava.