Search code examples
angularrxjsrxjs6rxjs-observables

Angular: are nested async pipe usage safe?


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?


Solution

  • 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.