简体   繁体   English

为什么结果不共享?

[英]Why result does not get shared?

I have following code snippet: 我有以下代码片段:

const source$ = Rx.Observable.from([1,2,3,4])
  .filter(x => x % 2)
  .map(x => x * x)
  .share();

source$.subscribe(x => console.log(`Stream 1 ${x}`));
source$.subscribe(x => console.log(`Stream 2 ${x}`));

As the result I've got 结果我得到了
在此处输入图片说明

But I am excepting shared results like: 但是我除了共享结果,例如:

"Stream 1 1"
"Stream 2 1"
"Stream 1 9"
"Stream 2 9"

Why the result does not get shared? 为什么结果无法共享?

This is because you're using a cold Observable ( http://reactivex.io/documentation/observable.html ). 这是因为您使用的是冷的Observable( http://reactivex.io/documentation/observable.html )。

When you subscribe for the first time it takes the refCount() operator and subscribes to its source Observable which is the Observable.from() . 首次订阅时,它将使用refCount()运算符并订阅其源Observable,即Observable.from() This all happens synchronously so it emits all its values the the subscriber and then emits complete which makes the refCount() unsubscribe from the source because there're no other Observers. 这一切都是同步发生的,因此它将所有值发送给订阅服务器,然后发送完成,这使refCount()取消订阅源,因为没有其他观察者。

Then you subscribe with the second Observer and this all happens again. 然后,您订阅第二个观察者,所有这些再次发生。

If you wanted to achieve your expected result that you could use just publish() to turn the source into a Connectable observable and call connect() manually. 如果您想达到预期的结果,则可以只使用publish()将源变成可连接的Observable并手动调用connect()

const source$ = Rx.Observable.from([1,2,3,4])
  .filter(x => x % 2)
  .map(x => x * x)
  .publish();

source$.subscribe(x => console.log(`Stream 1 ${x}`));
source$.subscribe(x => console.log(`Stream 2 ${x}`));

source$.connect();

See live demo: https://jsbin.com/waraqi/2/edit?js,console 观看现场演示: https : //jsbin.com/waraqi/2/edit?js,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM