BehaviorSubject initial value not working with share()

﹥>﹥吖頭↗ 提交于 2019-12-10 13:22:51

问题


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"

回答1:


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"


来源:https://stackoverflow.com/questions/42825763/behaviorsubject-initial-value-not-working-with-share

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!