Disposing of observables

5.7k Views Asked by At

This question is related to Android and life-cycles. Previously, I would have a series of subjects and subscribe to them on creation.

Upon destruction, I would mark all the subjects as complete, assuming that it disposes all subscribers.

With Android Studio 3.1, I get warnings for any subscriber that "isn't used". The solution is to add them to a "completable disposable" that I then dispose upon destruction.

Is "composite disposable" all I need to properly cancel requests upon destruction? Did my previous way of marking subjects as complete do anything and is it necessary in this case?

As a code example:

val observable: PublishSubject<Int> = PublishSubject.create()
val disposable = observable.subscribe { /* subscription */ }

fun onDestroy() {
    observable.onComplete() // is this line necessary or helpful?
    disposable.dispose()
}
2

There are 2 best solutions below

0
On BEST ANSWER

observable.onComplete() will complete your stream and so fire this event to all subscribers listening for onComplete, you don't need to dispose stream after onComplete (this is done automatically).

disposable.dispose() will stop stream and no complete event will be fired.

If you're not listenening for complete event both are the same, so to answer your question you don't need both lines.

2
On

Doing it on onDestroy is not a good idea because there is a gap between when the fragment/activity is stopped and when it's destroyed. If your observable fires during that gap, you will most likely do some UI work that will result in an exception, as you're attempting to manipulate UI objects after the activity/fragment was stopped.

A better approach is to offload this business logic to a viewmodel and then the UI listens for updates from the viewmodel via LiveData (which is itself lifecycle aware, so it takes care of subscribing/unsubscribing as needed). The code you showed here would then be moved to the viewmodel's onCleared method.

Check this and this for reference.