Search code examples
androidrx-java2

Is it recommended to call Disposable.dispose() as soon as a subscription completes work?


I have an Activity in which I am creating and subscribing to multiple instances of the Single class (each instance is doing some work in a separate background thread). For each subscription, I'm adding the Disposable instance that's created to a CompositeDisposable instance which is scoped to the Activity. When the Activity is destroyed, I am calling the CompositeDisposable.clear() method to dispose of all subscriptions in the Activity. This, of course, means that all Disposable instances (including those for subscriptions which have completed work) hang around in my Activity until the Activity is destroyed.

Is this okay or should I call Disposable.dispose() for each individual subscription every time the particular Single instance completes work (i.e. when the SingleObserver receives the onSuccess or onError callback)? The problem with the latter approach is that I have to keep track of which Disposable links to which SingleObserver, and this defeats the point of using CompositeDisposable.


Solution

  • No, you shouldn't. When an Observable is completed, Observable is disposed of by itself. This is part of the Observable contract:

    When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end the subscriptions that are ended by the Observable in this way.