O'Reilly logo

Reactive Android Programming by Tadas Subonis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Disposable

Since every .subscribe() call returns a Disposable interface, it is the easiest way to terminate Subscriptions that are no longer needed; they can be canceled with a reference to the returned object.

In a simplified case, it will look like this:

private Disposable disposable;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_mock);    disposable = Observable.interval(1, TimeUnit.SECONDS)            .subscribe();}@Overrideprotected void onDestroy() {    if (disposable != null) {        disposable.dispose();    }    super.onDestroy();}

Here, on the first line, we've created a field to keep a reference to the Disposable after it gets created:

private Disposable subscribe

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required