The RxLifecycle library makes it easier binding observable subscriptions to Android activities and fragment lifecycle.
Keep in mind that forgetting to unsubscribe an Observable can cause memory leaks and keeping your activity / fragment alive event after it has been destroyed by the system.
Add the library to the dependencies:
// use the last version available compile 'com.trello:rxlifecycle:0.6.1' compile 'com.trello:rxlifecycle-components:0.6.1'
You are all set, when you subscribe to an Observable you can now:
someObservable .compose(bindToLifecycle()) .subscribe();
If you execute this in the
onCreate() method of the activity it will automatically unsubscribed in the
Tha same happens for:
As an alternative you can specify the event when you want the unsubscription to happen:
From an activity:
someObservable .compose(bindUntilEvent(ActivityEvent.DESTROY)) .subscribe();
From a Fragment:
someObservable .compose(bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe();
You can also obtain the lifecycle observable using the method
lifecycle() to listen lifecycle events directly.
RxLifecycle can also be used directly passing to it the lifecycle observable:
If you need to handle
Completable you can do it by just adding respectively
forCompletable after the bind method:
someSingle .compose(bindToLifecycle().forSingle()) .subscribe();
It can also be used with Navi library.