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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mock);
disposable = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
}
@Override
protected 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;
Next, in the onCreate() block, we have the Observable and the Subscription created with this:
disposable = Observable.interval(1, TimeUnit.SECONDS)
.subscribe();
Also, we assign the Disposable reference.
Now, when the Activity is destroyed, the onDestroy() method will be called and the Subscription will be disposed of (canceled) with the following:
if (subscribe != null) {
subscribe.dispose();
}
The same can be done with onStart-onStop and onResume-onPause pairs. However, it is important not to mix up pairs (such as onStart-onDestroy) as it will most likely lead to leaks or inconsistent behavior of the application.