BehaviorSubject 初始值不适用于 share() [英] BehaviorSubject initial value not working with share()

查看:36
本文介绍了BehaviorSubject 初始值不适用于 share()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

share() 运算符应用于 BehaviorSubject.BehaviorSubject 有初始值.

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

目标是创建单个共享订阅.但是当 BehaviorSubject 具有初始值时,这种共享订阅似乎不起作用.

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

得到意想不到的结果.

代码如下:

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

结果:

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

预期结果:

"side effect"
"0 sub1"
"1 sub1"  <------------- this is missing from actual result
"side effect"
"1 sub1"
"1 sub2"

推荐答案

我明白这里有什么令人困惑的地方.

I understand what's confusing here.

BehaviorSubject 仅在订阅时发出.但是,您使用的是 share() 运算符,它在内部只是 publish()->refCount() 的简写.当第一个观察者订阅时,它会触发 refCount() 并订阅其源,这会导致 do() 中的副作用,并在观察者 0 sub1:

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"

然后你订阅另一个观察者,但这个订阅只对 publish() 操作符内的 Subject 类进行(这就是它的目的).所以第二个观察者不会收到默认的 0 也不会触发副作用.

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.

当你稍后调用 subject.next(1) 时,它会输出最后三行:

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

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

这篇关于BehaviorSubject 初始值不适用于 share()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆