The approach of manually tracking each Subscription might become unwieldy if there are multiple Subscriptions that need to be tracked in the same Activity. In this case, a CompositeDisposable might come in very handy. It's a class that can keep references to multiple Disposables and then unsubscribes from all of them at the same time.
So, consider this case:
Disposable disposable1 = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
Disposable disposable2 = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
Disposable disposable3 = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
Here, we have three Disposables that we would normally need to unsubscribe from with three calls to .dispose(). By introducing a CompositeDisposable:
private CompositeDisposable disposable;
disposable = new CompositeDisposable();
Disposable disposable1 = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
[...]
We can assign all the Disposables to CompositeDisposable with this:
disposable.addAll(
disposable1,
disposable2,
disposable3
);
Then, the onDestroy() block will look like before:
@Override
protected void onDestroy() {
if (disposable != null) {
disposable.dispose();
}
super.onDestroy();
}
Then, there will be no need for a separate .dispose() call to each Disposable.