使用Subject.create创建的主题无法退订 [英] Subjects created with Subject.create can't unsubscribe

查看:61
本文介绍了使用Subject.create创建的主题无法退订的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主题负责订阅某些可观察的内容:

I have a subject that is responsible for subscriptions to certain observable:

var timer$ = Rx.Observable.timer(1000, 2000);

将主题链接到这样的主题

When the subject is linked to the subject like that

var timerSubject = new Rx.Subject;
timer$.subscribe(timerSubject);

var subscription1 = timerSubject.subscribe(n => console.log(n));
var subscription2 = timerSubject.subscribe(n => console.log(n));

setTimeout(() => timerSubject.unsubscribe(), 4000);

一切都很好,timerSubject.unsubscribe()可以被调用一次,并且订阅不应该被一个一个地取消订阅.

everything is fine, timerSubject.unsubscribe() can be called once and the subscriptions shouldn't be unsubscribed one by one.

使用这样的Subject.create创建主题时( plunk )

When the subject is created with Subject.create like that (a plunk)

var timerSubject = Rx.Subject.create(null, timer$);

var subscription1 = timerSubject.subscribe(n => console.log(n));
var subscription2 = timerSubject.subscribe(n => console.log(n));

setTimeout(() => timerSubject.unsubscribe(), 4000);

timerSubject.unsubscribe()不执行任何操作,而我希望它的行为与第一个代码片段相同.

timerSubject.unsubscribe() does nothing, while I would expect to behave it the same as in the first snippet.

如果Subject.create创建了一个甚至无法退订的主题,那么Subject.create的目的是什么?

If Subject.create creates a subject that can't even unsubscribe, what's the purpose of Subject.create then?

为什么会这样?这是一个错误吗?

Why does this happen? Is this a bug?

应该如何创建主题以达到所需的行为?

How can the subject should be created to reach the desired behaviour?

它可以用RxJS 5 RC1复制.

It is reproducible with RxJS 5 RC1.

推荐答案

我检查了

I checked the source code for Subject.create() and it's not the same as calling new Subject().

  • Subject.create()返回AnonymousSubject的实例.

new Subject()返回Subject的实例.

所以看来AnonymousSubject上的unsubscribe()不起作用的问题是因为它实际上从未订阅.它仅保留对source Observable的引用,并且在订阅观察者时,它直接将source与观察者连接,并且不跟踪创建的订阅.

So it seems the problem why unsubscribe() on AnonymousSubject doesn't work is because it in fact never subscribes. It just keeps a reference to the source Observable and when subscribing an Observer it connects directly source with the Observer and doesn't keep track of created subscribtions.

在您的情况下,当您呼叫timerSubject.subscribe()时,它直接订阅timer$,而AnonymousSubject仅充当中介.

In your case when you call timerSubject.subscribe() it subscribes directly to timer$ and AnonymousSubject acts only as mediator.

我不知道这是设计使然还是错误.但是,我认为第一种选择更有可能.

I don't know whether this is by design or it's a bug. However, the first option is more likely I think.

这篇关于使用Subject.create创建的主题无法退订的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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