Search code examples
angulartimerrxjsobservableemit

RxJS handling success with async pipe


So basically I want to do following:

I have a backend call and template in Angular 6

After this backend call I want to switchMap the result to dataUpdated$ observable which will display something in template like:

<h1 *ngIf="dataUpdated$ | async">Very Good!</h1>

and then I want to set timer on the same stream and after lets say 2 seconds I want to update that observable again so it disappears in template.

I don't want to use subscribe method, I have subscription in code already.

I want to update to code to be one stream without breaking or needing to unsubscribe manually


Solution

  • The async pipe should keep only one subscription so you can use switchMap to just reemit the original value and after 2s emit false that should hide the message.

    dataUpdated$ = source.pipe(
      switchMap(v => merge(
        of(v),
        of(false).pipe(delay(2000)),
      )),
    );