问题
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