Understanding Async Pipe

VANDANA GUPTA
3 min readApr 11, 2021
Photo by Patrick Hendry on Unsplash

In this article, we will go through what is an async pipe and how to use it. A brief description of the async pipe is that it is a built-in angular feature and an impure pipe.

It subscribes to an observable or promise and returns the latest value that is emitted. When a new value is emitted from a promise or observable, the async pipe marks the component to be checked for changes. It creates a copy of the latest emitted output and displays the value directly in the template(screen). It even unsubscribes automatically when the component is destroyed so that memory leaks can be prevented.

The syntax for the async pipe is : {{ obj_expression | async}}

Input value to async is : subscribable/ Promise

Async Pipe with Promises

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div><h4>Promise Data without Async pipe</h4><p> {{promise}}</p></div>`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'async-pipe';
promise:string;
constructor
(){
this.getPromise().then(val=>this.promise=val);
}
getPromise():Promise<string>
{
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve("Here is the promise Data"),3000)});
}
}

We can see above when the promise is resolved, the data is stored in the promise property. In the constructor, we wait for the promise to get resolved, and finally, it is stored in the promise property. Through property binding, the value is visible in the template.

Now we will see how to use an async pipe in the template and save time by binding to the promise directly.

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div><h4>Promise Data with Async pipe</h4><p>{{promise|async}}</p></div>`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'async-pipe';
promise: Promise<string>
constructor() {
this.promise=this.getPromise()
}
getPromise(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Here is the promise Data"), 3000)})
}
}

As we can see above, the promise is unresolved and it is piped to the async pipe. Async pipe then returns a new value and displays it in the view. It saves time for writing then callback and storing the intermediate data.

Async pipes with observables

import { Component } from '@angular/core';
import { Observable, Subject, Subscription } from 'rxjs';
@Component({
selector: 'app-root',
template: `<div>
<h4>Observable without Async pipe</h4>
<p>{{observable}}</p>
</div>`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'async-pipe';
observable: string;
subscription: Subscription;
constructor() {
this.subscribeObservable()
}
getObservable() {
return new Observable<string>(observer => {
setTimeout(()=>observer.next("Here is the observable data"),3000)
})
}
subscribeObservable()
{
this.subscription=this.getObservable().subscribe(v => this.observable = v);
}
ngOnDestroy()
{
this.subscription.unsubscribe();
}
}

We can see above that we created an observable which publishes a string. We have to subscribe to the observable and then store the string in the observable property. Explicitly, we have to also unsubscribe the subscription in the ngOnDestroy lifecycle hook to avoid potential memory leaks.

Now let's see how to use async pipe with observable.

import { Component } from '@angular/core';
import { Observable, Subject, Subscription } from 'rxjs';
@Component({
selector: 'app-root',
template: `<div>
<h4>Observable with Async pipe</h4>
<p>{{observable|async}}</p>
</div>`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'async-pipe';
observable: Observable<string>
constructor() {
this.observable=this.getObservable()
}
getObservable() {
return new Observable<string>(observer => {
setTimeout(()=>observer.next("Here is the observable data"),3000)})
}
}

We can see above that we piped our observable directly to the async pipe. Async pipe performs the subscription to the observable and shows the data in the view. Async pipe also unsubscribes the subscription without using any life cycle hook. If we have multiple observables, we have to individually handle the unsubscribe part but the async pipe handles it on its own.

Overall, we saw that async pipe is quite a useful built-in feature of angular and can be used with promises and observable.

Thank you ✨✨

Happy coding !!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

VANDANA GUPTA
VANDANA GUPTA

Written by VANDANA GUPTA

An inquisitive person. A learner.

No responses yet

Write a response