Decision at Google about RxJS, Angular 2, TypeScript, Frontend, Async, RXJS, Angular, Typescript

Avatar of EyasSH
Software Engineer at Google ·
RxJSRxJSAngular 2Angular 2TypeScriptTypeScript

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

20 upvotes·2 comments·12.1K views
Mike Endale
Mike Endale
December 18th 2018 at 8:59pm

This is really amazing. Thanks for sharing

Boris Yakubchik
Boris Yakubchik
January 14th 2019 at 3:38pm

Thank you for sharing!

Avatar of Eyas Sharaiha

Eyas Sharaiha

Software Engineer at Google