rx-androidrx-java2activity-lifecycle

How can I subscribe and unsubscribe using onResume() and onPause() methods with RxJava 2?


Well, I need to bind emitting to my activity's lifecycle. How can I do that? And when should I create observer and observable instances?


Solution

  • If you have an observable that you want data from sometimes and not at other times, there is a simple way to subscribe and unsubscribe using the switchMap() operator.

    Let's say you have an observable that want data from:

    Observable<LocationData> locationDataObservable;
    

    Then, if you introduce a switching observable:

    PublishSubject<Boolean> switchObservable = PublishSubject.create();
    

    you can control the subscriptions to the first observable:

    Observable<LocationData> switchedLocationDataObservable =
      switchObservable
        .switchMap( abled -> abled ? locationDataObservable : Observable.never() )
        .subscribe();
    

    To enable receiving the data, perform

    switchObservable.onNext( Boolean.TRUE );
    

    and to disable,

    switchObservable.onNext( Boolean.FALSE );
    

    The switchMap() operator takes care of subscribing and unsubscribing for you.