Search code examples
androidrx-java2rx-kotlin2

Disposing of observables


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()
}

Solution

  • 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.