Search code examples
rxjs5behaviorsubject

BehaviorSubject as an observer


This code shows nothing in console. But if i change the second line with the commented code it works. Is this expected or something wrong here?

let bSubject = new BehaviorSubject<any>(1);
of(2).subscribe(bSubject); // of(2).subscribe(data => bSubject.next(data));
bSubject.subscribe(data => console.log(data));

Solution

  • The behavior is by-design.

    The first subscribe call sees the subject's complete method called, as the source observable completes.

    Once the subject's complete method is called, the BehaviorSubject is done and no further values will be emitted.

    That is, calling next on a completed BehaviorSubject will not emit a value and subscribing to a completed BehaviorSubject won't emit an initial value.

    When you replace the second line with:

    of(2).subscribe(data => bSubject.next(data));
    

    The subject's complete will no longer be called when the source observable completes and the subsequent subscription to the subject will emit the subject's current value.