RxJS share() operator with BehaviorSubject and async pipe – Angular


I have a BehaviorSubject that is being consumed as an observable:

testForStack$: Observable<boolean>;

    const bs = new BehaviorSubject(true);
    this.testForStack$ = bs
      .do(t => console.log('subscribed'))

This observable is being piped through three async pipes in the template:

Sub1: {{testForStack$ | async}}<br>
Sub2: {{testForStack$ | async}}<br>
Sub3: {{testForStack$ | async}}

The issue is only the first (Sub1) is getting the value of true

Sub1: true

If I remove the .share(), all three values get the value of true, but this causes the issue of multiple subscriptions.

Any thoughts on why using the BehaviorSubject causes this behavior? It’s being used as an observable so I would assume the above code would work correctly.

This is similar to this answer as well.


This is a correct behavior. The share() operator keeps only one subscription to its parent and BehaviorSubject emits its value only on subscription.

This means that when you use the first {{testForStack$ | async}} it subscribes at the end of the chain to share() which subscribes to its parents which results in subscribing to the source BehaviorSubject that emits its value immediately.

However, the second and all consecutive {{testForStack$ | async}} subscribe to share() which already has subscribed to its parent and won’t make any more subscriptions so there’s nothing to push the source value to these observers.

An easy solution could be using shareReplay(1) (depending on your RxJS version) you should probably use publishReplay(1).refCount() instead because of these issues (or its pipable equivalents):

Answered By – martin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published