Cache last emitted item RxJava Operator

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.

Tags:

Rx Java