Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache last emitted item RxJava Operator

Tags:

rx-java

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?

like image 673
Zeyad Gasser Avatar asked May 09 '17 01:05

Zeyad Gasser


2 Answers

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.

like image 144
Phoenix Wang Avatar answered Oct 07 '22 04:10

Phoenix Wang


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.

like image 43
yosriz Avatar answered Oct 07 '22 03:10

yosriz