user2649908
user2649908

Reputation: 575

RxJava async cache: proper way to dispose replay().autoConnect() Observable

I have to provide a short–lived cache for the result of the observable.

Looking at the options and I see following:

  1. cache replay(1).refCount() and when data is ready, cache the actual value. Cache retrieval would check actual data and do Observable.just or return pending Observable or initiate fresh request.

  2. cache replay(1).autoConnect(1) and always return that

latter seems more straight forward, but it has one caveat, how to correctly dispose observable when cache has to be invalidated.

There is a signature:

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

but hard to tell how I can track outstanding subscriptions and whether or not dispose will be graceful.

former will take care of resource deallocation, but you have to produce more complicated logic.

Upvotes: 5

Views: 984

Answers (1)

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

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);}
}

Upvotes: 0

Related Questions