Q:

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:

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. 
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.

A:

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

