RxJava2: Dispose an Observable chain

Sachin Chandil
AndroidPub
Published in
2 min readSep 24, 2017

--

If you are learning RxJava2 or already an experienced developer, you must be familiar with disposing Observable to prevent memory leaks. It is good practice to dispose complete observable chain running in your Activity or Fragment Life-Cycle.

A typical example of disposing an Observable:

In above example, you can see that in doTask() method, disposable is added to CompositeDisposable and in onStop observable is disposed using compositeDisposable.clear().

Looking so simple right? Yeah! but Hold On. Have a look at following snippet and try to simulate, how would this behave?

If i put current Activity or Fragment in background after around 9 seconds (suppose onStop() method is called), ideally following should be the expected output:

W/Debug:: First: 0
W/Debug:: Second: 0
W/Debug:: doONNext
W/Debug:: Second: 1
W/Debug:: doONNext
W/Debug:: Second: 2
W/Debug:: doONNext
W/Debug:: doOnDispose: observable has been disposed

But this is not how it works. This would work something like following:

W/Debug:: First: 0
W/Debug:: Second: 0
W/Debug:: doONNext
W/Debug:: Second: 1
W/Debug:: doONNext
W/Debug:: Second: 2
W/Debug:: doONNext
W/Debug:: doOnDispose: observable has been disposed
W/Debug:: Second: 3 // doOnNext is not called onward
W/Debug:: Second: 4
W/Debug:: First: 1
W/Debug:: First: 2
W/Debug:: First: 3
W/Debug:: First: 4

Isn’t it strange? It was for me when i was exploring it. It took me too long to figure out this as i found nothing regarding this on any blog, stackoverflow etc. So i asked a question on StackOverflow and got an answer that helped me out and that i am going to explain here.

So what just happened: Only immediate last observable (in this case doOnNext) got disposed and rest of the chain keeps on executing, do you know why? Lets understand: All operators has its own implementation of disposing itself except create operators(Observable.create, Single.create etc…), we have to implement create operator in way that can dispose itself. That is the reason only doOnNext operator got disposed(it already had implementation to dispose itself).

So how do we solve the issue? Lets dive into the solution.

To solve this issue we need to use isDisposed() method in Observables to check if Observable chain has been disposed. Have a look at following snippet.

As described in above example we need to use if(sbr.isDisposed()) return; to dispose that particular Observable. If there were four Observables, we would need to put this statement in all observables to terminate whole chain.

This is what i figured out to solve this issue, if you know something else please do share that, i would love to learn.

I hope this helps you in the journey of learning RxJava2. Please hit clap button to support and let others learn. Thanks for your love and support.

If you loved this i guess you would love following article too:

--

--