Unsubscribe on subject in RxJS

怎甘沉沦 提交于 2019-12-08 06:54:46

问题


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

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?


回答1:


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

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



来源:https://stackoverflow.com/questions/51894950/unsubscribe-on-subject-in-rxjs

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