The simplest way to use RxLifecycle in your code is to make your activities extend RxActivity:
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
public class ExampleLifecycleActivity extends RxAppCompatActivity {
}
Since we've extended RxActivity, we now have an access to the bindToLifecycle() method that can be used to terminate the Subscription. It can look something like this:
public class ExampleLifecycleActivity extends RxAppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mock);
Observable.interval(1, TimeUnit.SECONDS)
.compose(bindToLifecycle())
.subscribe();
}
}
The key call here is the following:
.compose(bindToLifecycle())
It modifies the Observable to listen to the events from the lifecycle of the Activity. When it finds an appropriate event--and in this case, it will be DESTROY (opposite of CREATE)--it will terminate the Subscription.
To test this ourselves, we can always add some logging and see what happens:
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose(() -> Log.i("APP", "Disposed"))
.compose(bindToLifecycle())
.subscribe();
After starting and navigating back from the Activity, we will see a message in the logs:
APP: Disposed
This means that the Subscription has been terminated and there is no task in the background that was leaked; however, before using .bindToLifecycle(), it would have kept running indefinitely.
Some readers might have noted that we've used the following class for the subclassing:
com.trello.rxlifecycle2.components.support.RxAppCompatActivity
There is also another one similarly named:
com.trello.rxlifecycle2.components.RxActivity
The difference is that the former one extends AppCompatActivity, and the latter extends Activity. So, if you have been using AppCompatActivity in your code before, you might want to stick to RxAppCompatActivity.