rx-java Android with RxJava RxLifecycle components


Example

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'

Then extends Rx* classes:

  • RxActivity / support.RxFragmentActivity / support.RxAppCompatActivity
  • RxFragment / support.RxFragment
  • RxDialogFragment / support.RxDialogFragment
  • support.RxAppCompatDialogActivity

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 onDestroy().

Tha same happens for:

  • onStart() -> onStop()
  • onResume() -> onPause()
  • onAttach() -> onDetach() (fragment only)
  • onViewCreated() -> onDestroyView() (fragment only)

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:

.compose(RxLifecycleAndroid.bindActivity(lifecycle))

If you need to handle Single or Completable you can do it by just adding respectively forSingle() or forCompletable after the bind method:

someSingle
    .compose(bindToLifecycle().forSingle())
    .subscribe();

It can also be used with Navi library.