Preventing Angular Subscription Memory Leaks

Subscribe to my newsletter and never miss my upcoming articles

Preventing Angular Subscription Memory Leaks

Don’t let your app get sluggish, handle your subscriptions

Handling Angular Subscriptions Properly

Handling Angular Subscriptions Properly

Photo by Kevin Ku on Unsplash

Bad Way of Handling Subscriptions

In my early Angular days, I would subscribe to observables without unsubscribing before the app was destroyed, possibly leading to a build up of memory leaks. For example:

Better Way

A simple way to avoid this is to save a reference to the subscription and unsubscribe in the ngOnDestroy lifecycle method. For example:

This is better, but what if you have a bunch of subscriptions in your component? There’s a nifty rxjs operator you can use for that.

You can create a subject, ngDestroy$ and pipe each subscription with the takeUntil operator. Now you can just add the .pipe(takeUntil(this.ngDestroy$)) before all subscriptions that you want to cancel when the component is destroyed.

Warning: if you have a method creating a subscription for each input change for instance the component below:

You could be possibly overlapping requests and previously requests that finish after subsequent ones can overwrite your fresh data. In this case, you want to make sure if you call the loadData method a second time, you cancel any previous requests first.

To solve this issue, you can either have a variable to store the subscription reference (solution 1) of the request in the loadData method, or you can reset the ngDestroy$ subscription every time before calling making the HTTP request again:

The above method somewhat limits the usefulness of the ngDestroy$ variable if you are using it for other requests as well, since those will be reset if the Input value changes.

Feel free to play around with the different methods and see what works for you with your particular circumstances!

If you like this article, check out my other articles on Angular and feel free to follow me to never miss a new article.

My Angular Tutorials on YouTube

No Comments Yet