For developers who work with Angular, for sure you have come across RxJS, it’s a cool library with the observable and its operators.
For observable, when it has been subscribed, it will return the subscription object which we have to unsubscribe to it when it has no use. eg the component gets destroyed. Otherwise, this can cause the memory leak
This article will explain to you the most 2 common ways to unsubscribe.
1. Put subscriptions into the array and unsubscribe to them after the component get destroyed.
From the following code, in ngOnInit method, we subscribe to selected customer and new order which both will return subscription then we push these 2 subscriptions into this.subscriptions array. Finally when the component gets destroyed ngOnInit method will be called, then we call RxJSUtil.unsubscribe to unsubscribe all of the subscriptions.
Note: I put unsubscribe as a static method in RxJSUtil class so it can be reused in many components.
2. Use takeUntil, the observable operator.
Instead of using an array to hold the subscription objects and unsubscribe to them later, the second method uses takeUntil operator to force observable to be complete. TakeUntil will listen until the Subject/Observable emit the value, then it will do the job.
Note: Make sure to put takeUntil as the last operator in the pipeline.
And that’s it, two simple ways to unsubscribe to the subscription, for the simplicity, I would suggest you use method 1, but there are some use cases that you will need to use method 2. (Make sure that takeUntil is the last operator in the pipeline)
Enjoy coding, guy!!!