What's the practical difference between observable.publish().refCount()
and observable.share()
. What would be an example of an scenario in which we don't want to use share
?
publish operator is a mechanism to introduce a Subject into the observable stream. This makes it possible to share a single subscription to the underlying stream between multiple subscribers.
sharelink. Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will unsubscribe from the source Observable.
There is no practical difference, if you look at 'observable.prototype.share' you will see that it simply returns 'source.publish().refCount()'.
As to why you would want to use it, it is more a question of how much control you need over when your source starts broadcasting.
Since refCount()
will attach the underlying observable on first subscription, it could very well be the case that subsequent observers will miss messages that come in before they can subscribe.
For instance:
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));
Only the first subscriber will receive any values, if we want both to receive them we would use:
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();
According to article "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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With