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

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.