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

后端 未结 2 1605
悲&欢浪女
悲&欢浪女 2021-02-07 15:02

What\'s the practical difference between observable.publish().refCount() and observable.share(). What would be an example of an scenario in which we do

相关标签:
2条回答
  • 2021-02-07 15:12

    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.

    0 讨论(0)
  • 2021-02-07 15:16

    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();
    
    0 讨论(0)
提交回复
热议问题