How can Observables (RxJava) helps with Android lifecycle (using compositeSubscription)

RxJava and Observables are no new topic in the Android and Java Domain. However there is still a good amount of developers that stay away for them. This is very natural since the concept of RxJava and Observable s is not easy to understand and it takes sometime until you get the aha moment.

Before that I have started to use them, I found it hard to understand why we need them to begin with. So I thought it would be cool to show one of the best used case for this pattern.

Let’s say that we have a screen, very simple one, just for fetching a Json from a server and display it. If we are using Retrofit (just for the sake of simplicity) it will look something like that :

So what can go wrong here? as most of you probably know there is a possible Null Pointer Exception that could positionally lead to a crash. That could happen if FetchingJsonActivity will be destroyed on the main thread while the working thread still fetching the Json, when it’s done the userView will be null and….BOOM — NPE.

Of course in that simple situation we can add a null check :

Mmm yes this will work but how does our code will look like with multiple network requests or other stuff related to lifecycle? is there a better way to solve this case? yes there is.

Let’s see how this looks like with Observables :

Okay this is slightly better, we are unsubscribing in onStop() which guarantees that the view won’t be null when the thread returns.

But what if we have multiple calls in the Activity? check this out :

Here we got two different network calls (could be unlimited number of them) and we are utilizing the power of CompositeSubscriptions, which is a container for subscriptions, to make those call “Life Cycle Aware”. Now we can focus about doing more cool thing in our app instead of checking for null all day.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.