When to Unsubscribe in Angular

Netanel Basal
Netanel Basal
Published in
2 min readApr 26, 2017

--

As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak.

Let’s see the most common cases that you will need to unsubscribe inside the ngOnDestroy lifecycle hook.

Forms —

This also applies to any form control.

The Router —

According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.

Renderer Service —

Infinite Observables —

When you have an infinite sequence, you should unsubscribe (unless you have a special case), for example when using the interval() or the fromEvent() observables.

Redux Store —

ngrx/store and redux-angular select method returns an observable. Therefore they have to be cleaned.

Don’t Unsubscribe

Async pipe —

When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

@HostListener —

Finite Observable —

When you have a finite sequence, it depends. I prefer always to unsubscribe. This is because we might have a code inside the observer that we don’t want to run upon destroying. I recommend examining the implications and decide.

Final tip —

You should be more declarative and try as little as possible to call the unsubscribe method. You can read more about the subject in this article — RxJS: Don’t Unsubscribe.

For example:

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.