问题描述
我正在为一些我不明白为什么会发生的事情而苦苦挣扎.
I'm struggling with something which I can't understand why it is happening .
看这个例子:
const source = Rx.Observable.of(1).share();
source.subscribe(console.log); //1
source.subscribe(console.log); //1
这会打印两次1".AFAIK share
查看 refCount
.但是如果我们看一下 - refcount
在这里应该为零:
This prints "1" twice. AFAIK share
looks at refCount
. But if we look at it - refcount
should be ZERO here :
const source = Rx.Observable.of(1).share();
source.subscribe(console.log);
^-- 1)refCount=1
2)value emitted - closing subscription ( complete)
3)refCount=0
source.subscribe(console.log);
^-- does refCount is 1 again or is it Zero ?
此外 - 当观察者未完成
const source = Rx.Observable.create((o)=>o.next(1)).share();
source.subscribe(console.log); //1
source.subscribe(console.log); //nothing
^这只会产生一个值
问题
我的 refCount 观察是否正确?为什么两个示例之间的结果不同?
Is my refCount observation was correct and why there are different results between the two examples ?
推荐答案
您的 refCount 观察是正确的.
Your refCount observation is correct.
在共享 Observable 上,如果(且仅当)refCount 重置为 0,则任何新订阅都将重新创建源 Observable.
On a shared Observable, if (and only if) the refCount resets to 0, then any new subscription would recreate the source Observable.
演示 1:每次订阅后引用计数重置
Demo 1: ref count resets after each subscription
演示 2:引用计数永远不会重置,因为订阅不会完成.
Demo 2: the refcount would never reset since the subscriptions won't complete.
第三个例子:
const source = Rx.Observable.create((o)=>o.next(1)).share();
source.take(1).subscribe(console.log); //1
source.take(1).subscribe(console.log); //1
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.8/Rx.js"></script>
这篇关于完成后,RxJS 的共享运算符的行为会有所不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!