当需要订阅我的observable时,我需要得到通知.我还需要通知观察者有错误或已完成.所以我认为我应该使用doOnSubscribe:
register an action to take when an observer subscribes to an
Observable
和doOnTerminate:
register an action to take when an Observable completes,either
successfully or with an error
然后我看到doOnUnsubscribe:
register an action to take when an observer unsubscribes from an
Observable
并认为doOnSubscribe / doOnUnsubscribe的对称性会更好.
那么,在doOnUnsubscribe之前是否会始终调用doOnTerminate?如果我只是想知道事情是“完成的”,那我选择哪个真的很重要?
最佳答案
在您的被动流程中取消订阅的方式将决定您可以使用doOnUnsubscribe或doOnTerminate中的哪一个.以下是可能的情况:
可观察的完成/错误触发取消订阅
在这种情况下,将首先调用doOnTerminate来调用doOnTerminate和doOnUnsubscribe.
以下示例将打印已终止和未订阅.
Subscription subscribe = Observable.empty() // source terminates immediately
.subscribeOn(Schedulers.newThread())
.doOnTerminate(() -> System.out.println("terminated"))
.doOnUnsubscribe(() -> System.out.println("unsubscribed"))
.subscribe();
TimeUnit.SECONDS.sleep(1);
subscribe.unsubscribe(); // by this time already unsubscribe would have happened
在Observable完成之前编程取消订阅
在这种情况下,只会调用doOnUnsubscribe.当你有一个无限运行的源或一个像用户点击可观察的热源这样的源时,这种情况发生的可能性更大.
以下示例仅打印未订阅.
Subscription subscribe = Observable.never() // source never terminates
.subscribeOn(Schedulers.newThread())
.doOnTerminate(() -> System.out.println("terminated"))
.doOnUnsubscribe(() -> System.out.println("unsubscribed"))
.subscribe();
TimeUnit.SECONDS.sleep(1);
subscribe.unsubscribe(); // this will trigger unsubscribe