`share()` 和 `publish().refCount()` 的区别
Difference between `share()` and `publish().refCount()`
observable.publish().refCount()
和 observable.share()
之间的实际区别是什么?我们不想使用 share
的场景示例是什么?
没有实际区别,如果你看一下 'observable.prototype.share' 你会发现它只是 returns 'source.publish().refCount()'.
至于为什么要使用它,更多的问题是当您的源开始广播时您需要多少控制权。
由于 refCount()
将在第一次订阅时附加底层可观察对象,因此后续观察者很可能会错过在他们订阅之前传入的消息。
例如:
var source = Rx.Observable.range(0, 5).share();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
只有第一个订阅者会收到任何值,如果我们希望两个都收到它们,我们将使用:
var source = Rx.Observable.range(0, 5).publish();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
source.connect();
根据文章“Rxjs Observable publish refcount vs share”;
With observable.publish().refCount(), once the observer completes, it
will not restart if a new subscriber is added after completion.
Whereas with observable.share(), if the underlying observer completes
and a new subscriber is added later, the observer effectively begins a
new execution and starts emitting data.
observable.publish().refCount()
和 observable.share()
之间的实际区别是什么?我们不想使用 share
的场景示例是什么?
没有实际区别,如果你看一下 'observable.prototype.share' 你会发现它只是 returns 'source.publish().refCount()'.
至于为什么要使用它,更多的问题是当您的源开始广播时您需要多少控制权。
由于 refCount()
将在第一次订阅时附加底层可观察对象,因此后续观察者很可能会错过在他们订阅之前传入的消息。
例如:
var source = Rx.Observable.range(0, 5).share();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
只有第一个订阅者会收到任何值,如果我们希望两个都收到它们,我们将使用:
var source = Rx.Observable.range(0, 5).publish();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
source.connect();
根据文章“Rxjs Observable publish refcount vs share”;
With observable.publish().refCount(), once the observer completes, it will not restart if a new subscriber is added after completion. Whereas with observable.share(), if the underlying observer completes and a new subscriber is added later, the observer effectively begins a new execution and starts emitting data.