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

后端 未结 2 1640
悲&欢浪女
悲&欢浪女 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: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();
    

提交回复
热议问题