Is it possible to get all the \"active\" subscriptions without storing them manually?
I\'d like to unsubscribe
all of the \"active\" subscriptions and don\'
You can inherit a Base component that implements the OnDestroy interface and keep an array to store all the Subscription and finally on destroy you can find the object with the instanceof Subscription and unsubscribe all. Let me write the code below.
export class BaseComponent implements OnInit, OnDestroy {
subscriptions: Subscription[] = [];
ngOnInit(): void {
}
ngOnDestroy(): void {
console.log('OnDestory - Baselass');
this.subscribers.forEach(sub => {
sub.unsubscribe();
console.log('Unsub');
})
}
addObserver(subscription: Subscription) {
this.subscribers.push(subscription);
}
}
export class SomeComponent extends BaseComponent implements OnInit, OnDestroy {
constructor(private someService: SomeService) {
super();
}
ngOnInit(): void {
super.ngOnInit();
}
ngOnDestroy(): void {
super.ngOnDestroy()
}
private initObservers() {
super.addObserver(this.someService.someObservable$.subscribe(res => {
}));
}
}
That's it, You don't now need to worry about unsubscribing a Subscription manually, BaseComponent with taking care of that.
Important point:- Pass the subscription to superclass is necessary, which keeps the list and unsubscribe all Subscriptions on component destroy lifecycle event.
super.addObserver(this.someService.someObservable$.subscribe(res => {
}));
Thanks!!