gpt4 book ai didi

rxjs - 共享 observable 和 startWith 运算符

转载 作者:行者123 更新时间:2023-12-04 07:18:00 33 4
gpt4 key购买 nike

我有一个关于多播 observables 和我注意到的意外(对我而言)行为的问题。

const a = Observable.fromEvent(someDom, 'click')
.map(e => 1)
.startWith(-1)
.share();

const b = a.pairwise();

a.subscribe(a => {
console.log(`Sub 1: ${a}`);
});

a.subscribe(a => {
console.log(`Sub 2: ${a}`)
});

b.subscribe(([prevA, curA]) => {
console.log(`Pairwise Sub: (${prevA}, ${curA})`);
});

因此,有一个共享的 observable a,它在每次点击事件时发出 1。由于 startWith 运算符而发出 -1。
可观察对象 b 只是通过配对来自 a 的最新两个值来创建一个新的可观察对象。

我的期望是:
[-1, 1] // first click
[ 1, 1] // all other clicks

我观察到的是:
[1, 1] // from second click on, and all other clicks

我注意到的是,值 -1 立即发出并由 Sub 1 消耗,甚至在 Sub 2 订阅 observable 之前,并且由于 a 是多播的,所以 Sub 2 对聚会来说为时已晚。

现在,我知道我可以通过 BehaviourSubject 进行多播而不使用 startWith 运算符,但是我想了解当我使用 startWith 和通过共享进行多播时这种场景的用例。

据我了解,每当我使用 .share() 和 .startWith(x) 时,只有一个订阅者会收到有关 startWith 值的通知,因为所有其他订阅者都是在发出该值后订阅的。

那么这是通过某些特殊主题(行为/重播...)进行多播的原因,还是我错过了有关此 startWith/share 场景的某些内容?

谢谢!

最佳答案

这实际上是正确的行为。
.startWith()向每个新订阅者发出其值(value),而不仅仅是第一个订阅者。原因b.subscribe(([prevA, curA])永远不会收到它是因为您正在使用多播与 .share() (又名 .publish().refCount())。

这意味着第一个 a.subscribe(...)使.refCount()订阅它的源,它会保持订阅状态(注意 Observable .fromEvent(someDom, 'click') 永远不会完成)。

然后当你最终调用b.subscribe(...)它只会订阅 Subject里面 .share()并且永远不会通过.startWith(-1)因为它已被多播并已在 .share() 中订阅.

关于rxjs - 共享 observable 和 startWith 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42021745/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com