# Preventing Angular Subscription Memory Leaks

<span class="s"></span>

# Preventing Angular Subscription Memory Leaks


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

![Handling Angular Subscriptions Properly](https://miro.medium.com/max/60/1*7_28h9D8qp0nRcak5JYTDg.jpeg?q=20)

<noscript><img alt="Handling Angular Subscriptions Properly" class="t u v ia aj" src="https://miro.medium.com/max/4800/1*7_28h9D8qp0nRcak5JYTDg.jpeg" width="2400" height="1799" srcSet="https://miro.medium.com/max/552/1*7_28h9D8qp0nRcak5JYTDg.jpeg 276w, https://miro.medium.com/max/1104/1*7_28h9D8qp0nRcak5JYTDg.jpeg 552w, https://miro.medium.com/max/1280/1*7_28h9D8qp0nRcak5JYTDg.jpeg 640w, https://miro.medium.com/max/1400/1*7_28h9D8qp0nRcak5JYTDg.jpeg 700w" sizes="700px"/></noscript>

Photo by [Kevin Ku](https://unsplash.com/@ikukevk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/coding?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

# 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](https://www.youtube.com/channel/UCTSZi5p3dzPfDYArmxDUJZA)
