RxJava Operator Last Emitted Cache

Is there a statement that caches the last posted item and passes it on to every new subscriber? In other words, an operator that makes an observable behave like an object BehaviorSubject

?

+7


source to share


2 answers


Yes. but in a third party library called ReplayingShare. Here is the link: https://github.com/JakeWharton/RxReplayingShare

Compare with .replay(1).autoConnect()

. It can disconnect from the uplink if there is no subscriber in the downstream direction.



Compare with .replay(1).refCount()

. It can also cache the last value even if you are already disconnected from it.

Also, if the upstream channel has ended (no matter which one you use refCount

/ autoConnect

), you won't get a replay for the next subscriber. But with ReplayingShare you always get your last item cache.

+9


source


Yes, you can use the operator replay(bufferSize)

with parameter 1 from the docs :

Returns a ConnectableObservable that shares one subscription to the original Observable that reproduces at most of the bufferSize elements emitted by this Observable



replay will cache the last item and replay it for any new subscriber, note that it is ConnectableObservable

, so you have to call connect()

it to start emitting items, or use refCount()

to fetch Observable

, which does it automatically from the first Subscriber

and unsubscribe when the last subscriber unsubscribed.

+5


source







All Articles