Is there an operator that caches the last emitted item and passes it to every new subscriber? In other words, an operator that makes an observable to behave like a BehaviorSubject
?
Yes. but in a 3rd party library called ReplayingShare. Here is the link: https://github.com/JakeWharton/RxReplayingShare
Compare to .replay(1).autoConnect()
It can disconnect from upstream if there are no subscriber at downstream.
Compare to .replay(1).refCount()
It can also cache the last value even you've already disconnected from it.
Also, if upstream ended (no matter which you use refCount
/autoConnect
), you won't get your replay for next subscriber. But with ReplayingShare you will always get your last item cache.
Yes, you can use replay(bufferSize)
operator with param of 1, from the docs:
Returns a ConnectableObservable that shares a single subscription to the source Observable that replays at most bufferSize items emitted by that Observable
replay will cache last item, and replay it to any new subscriber, please note that it's ConnectableObservable
so you must invoke connect()
to make it start emit items, or use refCount()
to get an Observable
that does it automatically with first Subscriber
, and unsubscribe when the last subscription unsubscribed.
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