0

I couldn't find any documentation related to this, so here it is. I have this usage of async pipe in a template:

<component [aliases]="(users$ | async).profile.aliases$ | async"/>

Is aliases$ subscription correctly unsubscribed when users$ emits? And what if there is an *ngIf on the wrapping element?

petronius
  • 451
  • 3
  • 11

1 Answers1

2

To avoid usage of multiple async pipes try this in the class

aliases$ = this.users$.pipe(
  switchMap(users => users.profile.aliases$),
)

<component [aliases]="aliases$ | async"/>

And regarding to your question about safety. Subscription to the inner observable will be alive. Check this stackblitz https://stackblitz.com/edit/angular-f88kfn.

If we dive into sources of AsyncPipe we find that pipe unsubscribes in ngOnDestroy hook. But it is not invoked if "outer" observable just has new value in "stream". So just use switchMap and one async pipe.

I Hope it helps.

Dmitrii Makarov
  • 757
  • 3
  • 11
  • Nice, I was indeed going for the switchMap solution just in case, but it's great to know the underlying behaviour. – petronius Apr 29 '20 at 12:38
  • Forked your stackblitz to check that in the case var1 && (obs1 | async) then obs1 was unsubscribed on var1 === false, and it is NOT the case. https://stackblitz.com/edit/angular-zkh9w6 – petronius Apr 29 '20 at 12:59