Canceling subscriptions

When an Activity or a Fragment gets destroyed, our chain could continue to run in the background, preventing the Activity from being disposed if the chain has references to the Activity or Fragment. When you no longer need the result of the chain, it could make sense to cancel the subscription and terminate the chain execution.

When we call the Observable.subscribe() function, it returns a Subscription object that can be used to terminate the chain immediately:

Subscription subscription = getTextFromNetwork(
               "http://demo1472539.mockable.io/mytet")
               ...
               .subscribe(new MySubscriber());

Again, the most appropriate Activity lifecycle method for this is onPause, which is guaranteed to be called before the Activity finishes:

protected ...

Get Asynchronous Android Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.