Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava- Is cache() the same as replay()?

I was wondering if there was a cache() operator that could cache x number of emissions but also expire them after a specified time interval (e.g. 1 minute). I was looking for something like...

Observable<ImmutableList<MyType>> cachedList = otherObservable
    .cache(1, 1, TimeUnit.MINUTES); 

This would cache one item but would expire and clear the cache after a minute.

I did some research and found the replay operator. It seemed like it would fulfill this need but I have some questions. Why is it hot and needs to be connected? Does this make it different than the cache() operator? I know the cache() mimics a subject, but it does not require being connected.

like image 967
tmn Avatar asked Sep 11 '15 11:09

tmn


1 Answers

cache and replay are meant for different use cases. Cache is an auto-connecting replay-everything container used typically for long-term replays. Replay can have more parametrization and can do bounded time/size replays but requires the developer to specify when to start. The autoConnect() operator lets you turn such ConnectableObservable instances to a plain Observable which connects to the source once a subscriber subscribes to them. This way, you can have a bounded and auto-connecting replay (requires RxJava 1.0.14+):

source.replay(1, TimeUnit.SECONDS).autoConnect().subscribe(...);
like image 126
akarnokd Avatar answered Nov 15 '22 22:11

akarnokd