Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `share()` and `publish().refCount()`

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?

like image 556
Sergi Mansilla Avatar asked Jun 07 '15 17:06

Sergi Mansilla


People also ask

What is publish in RXJS?

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.

What does RXJS share do?

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.


2 Answers

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();
like image 97
paulpdaniels Avatar answered Oct 11 '22 13:10

paulpdaniels


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.

like image 20
Teoman shipahi Avatar answered Oct 11 '22 12:10

Teoman shipahi