Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx - How to unsubscribe automatically after receiving onNext()?

How to unsubscribe automatically after receiving onNext() ?

For now I use this code:

rxObservable
.compose(bindToLifecycle()) // unsubscribe automatically in onPause() if method was called in onResume()
.subscribe(new Subscriber<Object>() {
     ...
     @Override
     public void onNext(Object o) {
         unsubscribe();
     }
 });
like image 518
Siarhei Sinelnikau Avatar asked Aug 11 '16 15:08

Siarhei Sinelnikau


People also ask

How do I unsubscribe from Observable Rxjava?

You need to cancel your job properly via Observable::create and Observable::flatMap. And set your cancalable in Observable::create.

What is RX Observable?

An Observable is analogous to a speaker that broadcasts the value. It does various tasks and generates some values. An Operator is similar to a translator in that it converts/modifies data from one form to another. An Observer is what fetches the value.


2 Answers

I you want to "unsubscribe" just after the first event, the operator take is a way to go.

 rxObservable.compose(bindToLifecycle())
             .take(1)
             .subscribe();
like image 79
dwursteisen Avatar answered Oct 02 '22 16:10

dwursteisen


I think this is what you need:

 rxObservable.compose(bindToLifecycle())
             .takeFirst(lifecycleEvent -> lifecycleEvent == LifecycleEvent.PAUSE);
like image 28
LenaYan Avatar answered Oct 02 '22 16:10

LenaYan