2
votes

I am new to Angular and RxJs and Ngrx

I know that we subscribe to an Observable and watch for changes. I came across this code in Ngrx getting started

<div>Current Count: {{ count$ | async }}</div>

Question is what exactly is AsyncPipe and how its different from subscribing to an Observable ? and when is one used and when the other?

2
It's not different really, it's how you subscribe in the template.jonrsharpe
Don't, then; it's up to you.jonrsharpe

2 Answers

5
votes

async pipe is much cleaner

data$ = this.service.data$;

and in the template

{{data$ | async}}

vs having to manage the subscription.

ngOnInit() {
  this.sub = this.service.data$.subscribe(data => { this.data = data });
}

ngOnDestroy() {
  this.sub.unsubscribe();
}

and in the template

{{data}}
1
votes

As @jonrsharpe mentioned it isn't really different. Under the hood the async pipe will create a subscription and store the most recent value which is the same thing that you would need to do if you wanted to subscribe and display the result.

The async pipe will also take care of unsubscribing from the observable when the component (the directive) is destroyed.

It may be slightly more efficient in terms of change detection but I'm not certain.

Mostly however, it is just used for convenience. It is less code to use an async pipe than it is to create a component variable and subscribe to it in the component's onInit or constructor and then keep track of the subscription to unsubscribe.