If you are using subscriptions in a component these should always be unsubscribed when the component is destroyed. In order to make it easier to handle subscriptions this class can be used.
-
Create an private attribute in your component something like that:
private subscrManager = new SubscriptionManager<Subscription>();
Alternatively you could just add it to your constructor:
constructor(private subscrManager: SubscriptionManager<Subscription>){...}
-
Wrap your subscription calls in:
this.subscrManager.add(someObservable.subscribe(...));
-
Implement OnDestroy and ngOnDestroy function like that:
ngOnDestroy(){ this.subscrManager.destroy(); }
-
That's all! This is a easy and secure way to handle Subscriptions :)
If you call the add() method it returns an ID that you can write to an variable. After that you can unsubscribe this subscription using removeById(id:number)
You can add a optional argument to an add
call for a string. This string is used as a tag. With removeByTag(tag:string)
all subscriptions with this tag will be unsubscribed. It's helpful if you need to group subscriptions.