Software Engineer at Google·
Shared insights
on
TypeScriptTypeScriptAngularAngularRxJSRxJS
at

One TypeScript / Angular 2 code health recommendation at Google is how to simplify dealing with RxJS Observables. Two common options in Angular are subscribing to an Observable inside of a Component's TypeScript code, versus using something like the AsyncPipe (foo | async) from the template html. We typically recommend the latter for most straightforward use cases (code without side effects, etc.)

I typically review a fair amount of Angular code at work. One thing I typically encourage is using plain Observables in an Angular Component, and using AsyncPipe (foo | async) from the template html to handle subscription, rather than directly subscribing to an observable in a component TS file.

Subscribing in components

Unless you know a subscription you're starting in a component is very finite (e.g. an HTTP request with no retry logic, etc), subscriptions you make in a Component must:

  1. Be closed, stopped, or cancelled when exiting a component (e.g. when navigating away from a page),
  2. Only be opened (subscribed) when a component is actually loaded/visible (i.e. in ngOnInit rather than in a constructor).

AsyncPipe can take care of that for you

Instead of manually implementing component lifecycle hooks, remembering to subscribe and unsubscribe to an Observable, AsyncPipe can do that for you.

I'm sharing a version of this recommendation with some best practices and code samples.

#Typescript #Angular #RXJS #Async #Frontend

READ LESS
Use AsyncPipe When Possible – Eyas's Blog (blog.eyas.sh)
28 upvotes·3 comments·1.1M views
Mike Endale
Mike Endale
·
December 18th 2018 at 8:59PM

This is really amazing. Thanks for sharing

·
Reply
Boris Yakubchik
Boris Yakubchik
·
January 14th 2019 at 3:38PM

Thank you for sharing!

·
Reply
Salman Arif
Salman Arif
·
December 30th 2023 at 10:11PM

which api protocol is used?

·
Reply
Avatar of Eyas Sharaiha

Eyas Sharaiha

Software Engineer at Google