Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject initial value not working with share()

share() operator is applied to a BehaviorSubject. BehaviorSubject has initial value.

Goal is to create a single shared subscribtion. But this shared subscribtion does not seem to work when BehaviorSubject has an initial value.

Getting unexpected results.

Code shown below:

let subject = new Rx.BehaviorSubject(0);
let published = subject
                  .do(v => console.log("side effect"))
                  .share();

published.subscribe((v) => console.log(v+" sub1"));
published.subscribe((v) => console.log(v+" sub2"));

subject.next(1);

Result:

"side effect"
"0 sub1"
"side effect"
"1 sub1"
"1 sub2"

Expected Result:

"side effect"
"0 sub1"
"1 sub1"  <------------- this is missing from actual result
"side effect"
"1 sub1"
"1 sub2"
like image 397
raneshu Avatar asked Mar 16 '17 05:03

raneshu


1 Answers

I understand what's confusing here.

The BehaviorSubject emits only on subscription. However, you're using the share() operator which internally is just a shorthand for publish()->refCount(). When the first observer subscribes it triggers the refCount() and it makes the subscription to its source which causes the side-effect in do() and also prints the default value in the observer 0 sub1:

"side effect"
"0 sub1"

Then you subscribe with another observer but this subscription is made only to the Subject class inside the publish() operator (that's what it's made for). So the second observer won't receive the default 0 nor trigger the side effect.

When you later call subject.next(1) it'll made the last three lines of output:

"side effect"
"1 sub1"
"1 sub2"
like image 68
martin Avatar answered Sep 28 '22 06:09

martin