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

对着背影说爱祢 提交于 2021-02-07 05:05:12

问题


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();
     }
 });

回答1:


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

 rxObservable.compose(bindToLifecycle())
             .take(1)
             .subscribe();



回答2:


I think this is what you need:

 rxObservable.compose(bindToLifecycle())
             .takeFirst(lifecycleEvent -> lifecycleEvent == LifecycleEvent.PAUSE);


来源:https://stackoverflow.com/questions/38900610/rx-how-to-unsubscribe-automatically-after-receiving-onnext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!