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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With