RxJava async cache: the correct way to dispose of replay (). AutoConnect () Observable

I have to provide a short-term cache for the result of the observable.

Looking at the options, and I see the following:

  • cache replay(1).refCount() and when the data is ready, cache the actual value. A cache search will check the actual data and do Observable.just or return a Pending Observed or initiate a new request.

  • cache replay(1).autoConnect(1) and always return

the latter seems more direct, but it has one caveat on how to properly handle the observable when the cache should be invalid.

There is a signature:

public Observable<T> autoConnect(int numberOfSubscribers, Consumer<? super Disposable> connection)

but it's hard to say how I can track outstanding subscriptions and whether recycling will be elegant.

the former will take care of freeing up resources, but you must create more complex logic.

+5
source share
1 answer

Why not .cache() ?

 public class CachedObservable<K,V> { private Function<K, Observable<V>> actual; private CachedObservable(Function<K, Observable<V>> actual){this.actual=actual;} private final Map<K, Observable<V>> cacheMap = new ConcurrentHashMap<>(); public Observable<V> get(K key) { return cacheMap.computeIfAbsent(key, k -> this.actual.call(k).cache()); } public void invalidate(K key){cacheMap.remove(key);} } 
0
source

Source: https://habr.com/ru/post/1265150/


All Articles