In my component template I am calling async
pipe for same Observable in 2 places.
Shall I subscribe to it and use returned array in my template or using async
pipe for same Observable in multiple places of template has no negative effect to performence?
Best Answer
Every use of
observable$ | async
will create a new subscription(and therefor an individual stream) to the givenobservable$
- if this observable contains parts with heavy calculations or rest-calls, those calculations and rest-calls are executed individually for eachasync
- so yes - this can have performance implications.However this is easily fixed by extending your
observable$
with.share()
, to have a shared stream among all subscribers and execute all those things just once for all subscribers. Don't forget to add theshare
-operator withimport "rxjs/add/operator/share";
The reason why async-pipes don't share subscriptions by default is simply flexibility and ease of use: A simple
.share()
is much faster to write than creating a completely new stream, which would be required if they were to be shared by default.Here is a quick example