When to use doOnTerminate vs doOnUnsubscribe?

主宰稳场 提交于 2019-12-07 03:30:39

问题


I need to be notified when something subscribes to my observable. I also need to be notified that the observable has either errored or completed. So I thought I should use doOnSubscribe:

register an action to take when an observer subscribes to an Observable

and doOnTerminate:

register an action to take when an Observable completes, either successfully or with an error

Then I saw doOnUnsubscribe:

register an action to take when an observer unsubscribes from an Observable

and thought the symmetry of doOnSubscribe/doOnUnsubscribe would be better.

So, will doOnTerminate always be called before doOnUnsubscribe? If I just want to know that things are "done", does it really matter which I choose?


回答1:


The way unsubscribe happens in your reactive flow will determine which one from doOnUnsubscribe or doOnTerminate you can use. The following can be the cases:

Observable completion/error triggers unsubscribe
In such a scenario both doOnTerminate and doOnUnsubscribe will be called with doOnTerminate being called first.

The below example will print both terminated and unsubscribed.

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

Programatic call to unsubscribe before Observable completes
In such a scenario only doOnUnsubscribe will be called. The chance of this happening is more prevalent when you have a source which runs infinitely or a source which is hot like an observable for user clicks.

The below example will only print unsubscribed.

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


来源:https://stackoverflow.com/questions/40407842/when-to-use-doonterminate-vs-doonunsubscribe

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