Reputation: 583
I subscribed to a Subject
using the subscribe()
method on the Subject
class. To unsubscribe I see two options, since the unsubscribe()
method is available on both Subject
and Subscription
classes.
Subscription
which is returned by subject.subscribe()
methodngOnInit() {
this.subscription = this.subject.subscribe(next => nextHandler(), err => errHandler());
}
ngDestroy() {
this.subscription.unsubscribe();
}
unsubscribe()
method directly on the subject like subject.unsubscribe()
ngOnInit() {
this.subject.subscribe(next => nextHandler(), err => errHandler());
}
ngDestroy() {
this.subject.unsubscribe();
}
What is the correct way of unsubscribing.
Upvotes: 5
Views: 850
Reputation: 35
Assume Subject as a News Paper which will send you a stream of events every day and subscription is related to users subscription.
Subject.unsubscribe()
When you do this, you actually want to destroy the newspaper itself, you should not be doing that.
Subscription.unsubscribe()
When you do this, you are just unsubscribing the subscription to which you have subscribed. not the source(Subject).
See the demo below: https://stackblitz.com/edit/typescript-umf1tv
Upvotes: 2
Reputation: 96891
The only difference I'm aware of is that when using Subject.unsubscribe()
it won't trigger any dispose handlers created by piping operators.
import { Subject } from 'rxjs';
import { finalize } from 'rxjs/operators';
const subject = new Subject();
const subscription = subject
.pipe(
finalize(() => console.log('done')),
)
.subscribe();
subject.unsubscribe();
// subscription.unsubscribe();
This will never print done
to the console because Subject.unsubscribe()
only removes all observers. https://github.com/ReactiveX/rxjs/blob/master/src/internal/Subject.ts#L105
While using subscription.unsubscribe()
will trigger finalize
's dispose handler which is probably the more predictable behavior.
Live demo: https://stackblitz.com/edit/rxjs-z5fjh1
Upvotes: 4