Reputation: 63
In my angular project, I have multiple subscriptions in a few components. So I use properties inside of it to store subscriptions, and in destroy function, I unsubscribe all of them. The problem is that the code becomes larger unnecessary larger. My question is, is there any way to unsubscribe all subscriptions at ones?
Upvotes: 1
Views: 6084
Reputation: 21397
There is many ways to do that but we can't avoid the boilerplate, you can use the ways above or use a decorator for that but keep in mind that there are exceptions where you don't have to unsubscribe:
No Need of unsubscribe in these cases
In case of HttpClient calls because the observable emit one value (success or error) and complete automatically.
In case or ActivatedRoute subscription because the Router will destroy it when the component is destroyed automatically
use of Async pipe
Upvotes: 1
Reputation: 4987
A recommanded way to unsubscribe to an observable is to call
ngOnDestroy () {
this.obs.next();
this.obs.complete();
}
To do it for all observable at once, you can declare a subject and use takeUntil
from rxjs :
ngUnsubscribe = new Subject();
... code...
ngOnInit() {
this.myObs.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(_ => ...);
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
I do it this way because I noticed that in my project, calling .unsubscribe()
wasn't working as expected. Switching from component A to B and then back to A created a second (then third, etc.) subscription and finally fixed by applying advice from this thread).
Upvotes: 0
Reputation: 29355
I tend to store all my subscriptions in an array..
private subs: Subscription[] = []
ngOnInit() {
this.subs.push(
this.obs1.subscribe(),
this.obs2.subscribe() // etc
)
}
ngOnDestroy() {
this.subs.forEach(s => s.unsubscribe())
}
other people prefer other methods. just be creative.
Upvotes: 6