Why Use The Async Pipe

What is the Async Pipe?

In Angular, we have the concept of the pipe function. A pipe function takes data as input and transforms it to the desired output.

We commonly use these in our templates. By using the | pipe operator within a template expression we can modify a view right within our template:

<p>The wedding is on {{ wedding | date }}.</p>

Here we are using the built-in DatePipe. One other built-in pipe we have at our disposal is the AsyncPipe.

The AsyncPipe is a bit more special - in that it just doesn’t take in input and transform it to the desired output. It does the following:

  1. Subscribes to an observable or a promise - returning the last emitted value.
  2. Whenever a new value is emitted, it marks the component to be checked.
  3. It automatically unsubscribes from observable when component is destroyed.

Why Should We Use It?

Less Code

Of course, we can manage async state directly in our component logic. Here’s an example of that:

this.exampleSub = this.exampleService.value$.subscribe(value => {
    this.example = value;
});

Oh, but we also have to make sure we are cleaning up this subscription:

ngOnDestroy(): void {
    this.exampleSub.unsubscribe();
    // ...
}

Instead, let’s do all this in the template:

<your-component [yourValue]="yourObservable$ | async"></your-component>

All the code you need to subscribe and unsubscribe in the component is now gone. This lends itself to less chances of a memory leak and to better performance.

Change Detection Strategy

Another big win of this approach is when using the OnPush change detection strategy. We can reduce our change detection cycle time dramatically through the use of this strategy.

It just so happens that the async pipe marks the component to be checked if the object changes, saving us the manual labor.

The manual labor looks like:

this.exampleSub = this.exampleService.value$.subscribe(value => {
    //...
    this.changeDetectorRef.markForCheck();
});

Again, more code. More places to create bugs. We avoid this by letting the pipe handle it.

Conclusion

Overall, using the AsyncPipe is a powerful tool that enables thinner components that can be optimized further by using the OnPush strategy easily. Seems like a good deal.


Erik August Johnson is a software developer working with JavaScript to build useful things. Follow them on Twitter.