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?
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.