The difference between `share ()` and `publish (). RefCount () `

What is the practical difference between observable.publish().refCount() and observable.share() . What will be an example scenario where we do not want to use share ?

+7
javascript rxjs
source share
1 answer

There is no practical difference if you look at "observable.prototype.share", you will see that it simply returns "source.publish (). RefCount ()".

As for why you would like to use it, it is more a matter of how much control you need when your source starts broadcasting.

Since refCount() will be attached to the base observable during the first subscription, it is possible that subsequent observers will skip the messages that come in before they can subscribe.

For example:

 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 of them to be received, we will 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(); 
+11
source share

All Articles