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?
- First, it automatically subscribes to the observable, so we no longer need to call
.subscribe()
. - It returns the data from that observable, triggering Angular’s change detection when needed for our component to display the latest data.
- 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.