How to avoid memory leaks with RxJs observables?

The easiest way to get in trouble in a big Angular application is to create a memory leak by not unsubscribing from your observables. While there are different techniques to unsubscribe your observables automatically, one is more concise, elegant, and overall the most error-proof.

That technique is to use the async pipe from the Angular framework.

Why is the async pipe such a great tool?

  1. First, it automatically subscribes to the observable, so we no longer need to call .subscribe().
  2. It returns the data from that observable, triggering Angular’s change detection when needed for our component to display the latest data.
  3. Finally, it automatically unsubscribes from the observable when our component is destroyed.

All of that with just 6 characters! (ok, perhaps a bit more if you want to count the whitespace):

<div>{{myObservable | async}}</div>Code language: HTML, XML (xml)

The async pipe works exactly like the code we would write (and thus duplicate over and over again, making our code base larger and thus our code slower) if we didn’t use it.

Check its source code here, and you’ll see that all it does is implement ngOnDestroy to unsubscribe from our observable.

There isn’t any good reason not to use the async pipe, and if you think you have some, stay tuned for our next messages, as we’ll cover some nice tips and tricks around using that pipe.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.