Why does publishReplay(1).refCount() not replay the last value for late subscribers?
a = new Rx.Subject();
b = a.publishReplay(1).refCount();
a.subscribe(function(x){console.log('timely subscriber:',x)});
a.next(1);
b.subscribe(function(x){console.log('late subscriber:',x)});
<script src="http://reactivex.io/rxjs/user/script/0-Rx.js"></script>
Expected output:
timely subscribe: 1
late subscriber: 1
Actual output
timely subscriber: 1
This happens because at the time you call a.next(1)
the publishReplay(1)
hasn't subscribed to its source Observable (Subject a
in this case) and therefore the internal ReplaySubject
won't receive the value 1
.
In RxJS 5 the actual subscription between operators happens when you subscribe at the end of the chain which is b.subscribe(...)
in this example. See:
Until you call subscribe()
the operators are chained thanks to lift()
method that just takes an instance of operator and assigns it to the new Observable. The operator.call()
method as you can see in the two links above is called later when subscribing. See:
Your first subscriber subscribes to a
, since refCount
first activates the stream when there is at least 1 subscriber (of which there is none, because not b
but a
is subscribed), it is not active until your last loc.
a = new Rx.Subject();
b = a.publishReplay(1).refCount();
b.subscribe(function(x){console.log('timely subscriber:',x)});
a.next(1);
b.subscribe(function(x){console.log('late subscriber:',x)});
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With