The use case is this: I want to temporarily cache the latest emitted expensive Observable response, but after it expires, return to the expensive source Observable and cache it again, etc.
A pretty basic network cache scenario, but I’m really struggling to get it working.
private Observable<String> getContentObservable() { // expensive upstream source (API, etc.) Observable<String> sourceObservable = getSourceObservable(); // cache 1 result for 30 seconds, then return to the source return sourceObservable .replay(1, 30, TimeUnit.SECONDS) .autoConnect() .switchIfEmpty(sourceObservable); }
Initial request: goes to source Second request within 30 seconds of source emitting: delivered from cache Third request outside of cache expiry window: nothing. I subscribe to it and I get no data, but it’s not switching to the upstream source Observable.
It looks as if I’m just connecting to my ConnectableObservable from autoConnect()
and it’s never completing with empty, so it’s never triggering my switchIfEmpty()
.
How can I use this combination of replay(1,x,x)
and switchIfEmpty()
?
Or am I just approaching this wrong from the start?
Answer
So it’s turns out you can use Jake Wharton’s replaying share to cache the last value even after dispose. https://github.com/JakeWharton/RxReplayingShare