Reputation: 3436
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?
Upvotes: 3
Views: 4696
Reputation: 3436
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
Upvotes: 4