Márió Posta
Márió Posta

Reputation: 173

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?

Upvotes: 1

Views: 938

Answers (2)

Ilya Mashin
Ilya Mashin

Reputation: 954

It can be solved without Observable.never(). Just use BehaviourSubject with takeUntil and repeatWhen operators.

private fun getPauseUpdatesSource(): Flowable<Unit> {
    return setUpdatesPausedSubject
        .filter { it }
        .map { }
        .toFlowableLatest()
}

private fun getResumeUpdatesSource(): Flowable<Unit> {
    return setUpdatesPausedSubject
        .filter { it.not() }
        .map { }
        .toFlowableLatest()
}

And in the rx chain:

locationDataObservable
                .takeUntil(getPauseUpdatesSource())
                .repeatWhen { it.switchMap { getResumeUpdatesSource() } }

It just pauses your chain and doesn't emit any empty observables

Upvotes: 1

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

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.

Upvotes: 4

Related Questions