DEV Community

Tomas
Tomas

Posted on

You don't need to care about unsubscribing

Problem:
Not unsubscribing to observables can cause memory leaks. Unsubscribing is fairly straight forward but could easily be forgotten and cause a fair amount of boilerplate code.

Solution:
By using Angulars builtin async pipe, we don't need to subscribe or unsubscribe, it's handle automatically for us by the framework.

Before / Untutored:

Component

export class AppComponent implements OnInit, OnDestroy {

  recipe;
  componentDestroyed$: Subject<boolean> = new Subject();

  constructor(private recipesService: RecipesService) {  }

  ngOnInit() {
    this.recipesService.get().pipe(takeUntil(this.componentDestroyed$)).subscribe(data => this.recipe = data);
  }

  ngOnDestroy() {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }
}

Template

{{ recipe }}

After:

Component

export class AppComponent implements OnInit {

  recipeWithAsyncPipe$;

  constructor(private recipesService: RecipesService) {  }

  ngOnInit() {
    this.recipeWithAsyncPipe$ = this.recipesService.get();
  }
}

Template

{{ recipe$ | async }}

Try it yourself:
https://stackblitz.com/edit/thllbrg-angular-fika-4

Official docs:
https://angular.io/guide/observables-in-angular#async-pipe

Top comments (0)