4

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?

dota2pro
  • 7,220
  • 7
  • 44
  • 79

2 Answers2

8

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}}
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
2

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.

Pace
  • 41,875
  • 13
  • 113
  • 156
  • I think the main differene is async pipe subscribes to an Observable or Promise, you can use Async with a Promise too and same is not true for Subscription ? – dota2pro May 06 '19 at 20:39
  • 2
    It is definately more effecient if you change you components to use changeDetection: ChangeDetectionStrategy.OnPush – Adrian Brand May 06 '19 at 23:58
  • 1
    @dota2pro The syntax is different but you should be able to get the result from a promise into a local component variable just like you can for an observable. – Pace May 07 '19 at 05:22