Subjects created with Subject.create can't unsubscribe

守給你的承諾、 提交于 2019-11-28 08:48:52

问题


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);

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

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() does nothing, while I would expect to behave it the same as in the first snippet.

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?

It is reproducible with RxJS 5 RC1.


回答1:


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

  • Subject.create() returns an instance of AnonymousSubject.

  • new Subject() returns an instance of Subject.

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.

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.



来源:https://stackoverflow.com/questions/40159886/subjects-created-with-subject-create-cant-unsubscribe

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