Hikmat G.
Hikmat G.

Reputation: 2621

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));

Upvotes: 1

Views: 418

Answers (1)

cartant
cartant

Reputation: 58400

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.

Upvotes: 3

Related Questions