本文介绍了何时使用 doOnTerminate 与 doOnUnsubscribe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有东西订阅了我的 observable 时,我需要得到通知.我还需要被通知 observable 已出错或已完成.所以我想我应该使用 doOnSubscribe:

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:

注册当观察者订阅时采取的行动可观察

doOnTerminate:

注册一个 Observable 完成时要执行的操作,或者成功或有错误

然后我看到了doOnUnsubscribe:

注册当观察者取消订阅时要采取的行动可观察

并认为 doOnSubscribe/doOnUnsubscribe 的对称性会更好.

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

那么,doOnTerminate 是否总是在 doOnUnsubscribe 之前被调用?如果我只想知道事情已经完成",那么我选择哪个真的重要吗?

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?

推荐答案

在响应式流程中取消订阅的方式将决定您可以使用 doOnUnsubscribedoOnTerminate 中的哪一个.可能是以下情况:

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:

可观察到的完成/错误触发取消订阅
在这种情况下,doOnTerminatedoOnUnsubscribe 都将被调用,doOnTerminate 将首先被调用.

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

下面的示例将打印 terminationunsubscribed.

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

在 Observable 完成之前取消订阅的程序调用
在这种情况下,只会调用 doOnUnsubscribe.当您有一个无限运行的源或一个像用户点击的 observable 一样热的源时,发生这种情况的可能性更大.

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.

下面的例子只会打印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

这篇关于何时使用 doOnTerminate 与 doOnUnsubscribe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 13:27