Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: many Async pipes vs one subscribe

What is better for performance and "angular way": have many async pipes in the view or one subscriber in the component with unsubscribe action onDestroy?

Example:

@Component({
  template: `<div> {{ post.title }} {{ post.author.name }} {{ post.category.name }} </div>`
  ...
  })
class AppComponent {
  public post: Post;
  public postSubscription;

  ngOnInit() {
    postSubscription = someObservable.subscribe((post) => {
      this.post = post;
    })
  }

 ngOnDestroy() {
    postSubscription.unsubscribe();
 }
}

or

@Component({
  template: `<div> {{ postTitle | async }} {{ postAuthorName | async }} {{ postCategoryName | async }} </div>`
  ...
  })
class AppComponent {
  public postTitle: Observable<string>;
  public postAuthorName: Observable<string>;
  public postCategoryName: Observable<string>;

  ngOnInit() {
    this.postTitle = someObservable.pluck('title');
    this.postAuthorName = someObservable.pluck('author', 'name');
    this.postCategoryName = someObservable.pluck('category', 'name');
  }
}
like image 394
dakolech Avatar asked Aug 18 '16 09:08

dakolech


People also ask

Does async pipe create a new subscription?

Async pipe creationOn the first call to transform, a subscription will be created from the observable we passed in. If our observable emits a new value, the display value ( this. _latestValue ) will be updated. Note, obj is the observable we've passed in, also known as the source observable.

Does angular async pipe unsubscribe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Why we use pipe with subscribe in angular?

The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.


1 Answers

Using the | async pipe is more efficient because Angular gets notified about changes. With the first example the bindings are checked each change detection cycle.

like image 113
Günter Zöchbauer Avatar answered Oct 14 '22 08:10

Günter Zöchbauer