RxJS's share operator behaves differently when complete?

两盒软妹~` 提交于 2019-12-11 11:06:11

问题


I'm struggling with something which I can't understand why it is happening .

Looking at this example :

 const source = Rx.Observable.of(1).share();

 source.subscribe(console.log); //1
 source.subscribe(console.log); //1

This prints "1" twice. AFAIK share looks at refCount. But if we look at it - refcount should be ZERO here :

const source = Rx.Observable.of(1).share();

 source.subscribe(console.log); 
             ^--  1)refCount=1
                  2)value emitted - closing subscription ( complete)
                  3)refCount=0

 source.subscribe(console.log);
            ^-- does refCount is 1 again or  is it Zero ?

DEMO 1

Also - Things get more complicated when the observer is not completed

const source = Rx.Observable.create((o)=>o.next(1)).share();

 source.subscribe(console.log); //1
 source.subscribe(console.log); //nothing

^This only yield one value

Demo2

Question

Is my refCount observation was correct and why there are different results between the two examples ?


回答1:


Your refCount observation is correct.

On a shared Observable, if (and only if) the refCount resets to 0, then any new subscription would recreate the source Observable.

Demo 1: ref count resets after each subscription

Demo 2: the refcount would never reset since the subscriptions won't complete.

A third example:

const source = Rx.Observable.create((o)=>o.next(1)).share();

source.take(1).subscribe(console.log); //1
source.take(1).subscribe(console.log); //1
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.8/Rx.js"></script>


来源:https://stackoverflow.com/questions/49561125/rxjss-share-operator-behaves-differently-when-complete

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!