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.
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(...);
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