15

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();
     }
 });
Siarhei Sinelnikau
  • 423
  • 1
  • 6
  • 12

2 Answers2

28

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

 rxObservable.compose(bindToLifecycle())
             .take(1)
             .subscribe();
dwursteisen
  • 11,435
  • 2
  • 39
  • 36
1

I think this is what you need:

 rxObservable.compose(bindToLifecycle())
             .takeFirst(lifecycleEvent -> lifecycleEvent == LifecycleEvent.PAUSE);
LenaYan
  • 746
  • 6
  • 7