在 RxJS 中取消订阅主题 [英] Unsubscribe on subject in RxJS

查看:35
本文介绍了在 RxJS 中取消订阅主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现以下构造让我有点困惑(打字稿中提供了示例):

I found following construct a bit confusing for me (example provided in typescript):

let someSubject: Subject<any> = new Subject();
let subscription1: Subscription = someSubject.subscribe((v) => {console.log(v)})
let subscription2: Subscription = someSubject.subscribe((v) => {console.log(v)})

很明显,我可以(并且应该)像这样取消订阅待定订阅:

Its obvious that I can (and should) unsubscribe from pending subscription like so:

subscription1.unsubscribe();
subscription2.unsubscribe();

但是Subject 类确实有一个成员方法unsubscribe.这与主题既是 Observable 又是 Observer 的方法一致,但是从我在执行以下操作时实际上取消订阅的内容来看:

But the Subject class do have a member method unsubscribe. It's coherent with approach that subject is both Observable and Observer, but from what I'm actually unsubscribing when doing following:

someSubject.unsubscribe();

我是否要取消与此主题相关的所有其他订阅?

Am I cancelling all other subscriptions attached to this subject?

推荐答案

看起来我提出问题有点匆忙.无论如何,因为我认为这没有得到很好的记录并且如果您通过某些共享服务提供您的主题可能会导致可怕的错误,下面是示例代码:

Looks I rushed a bit with a question. Anyway, because I think this in not well documented and may cause horrible errors if you providing your subject via some shared service, below is example code:

a = new Rx.Subject();

a.next(5) // No console log
s1 = a.subscribe((v) => console.log(v));
s2 = a.subscribe((v) => console.log(v*2));
a.next(5); // 5 & 10 will print out
s2.unsubscribe();
a.next(5); // 5  will print out
s2 = a.subscribe((v) => console.log(v*2)); // I can legally attach/reattach subscriber
a.next(5); // 5 & 10 will print out
a.unsubscribe(); // shut down WHOLE subject
a.next(5) // Will cause ObjectUnsubscribedError
s2 = a.subscribe((v) => console.log(v*2)) // Will cause ObjectUnsubscribedError

要点是 unsubscribe 不仅会关闭整个主题(使其无法发出和订阅它),还会清除所有内部观察者数组.所以没有人会再收到这个主题的通知

Takeaway is that unsubscribe will not only shut down whole subject (making it impossible to emit and subscribe to it) but will clear out all internal observers array. So nobody will be ever notified again by this subject

这篇关于在 RxJS 中取消订阅主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆