use*_*908 5 java observable rx-java
我必须为observable的结果提供一个短期缓存.
看看选项,我看到以下内容:
缓存replay(1).refCount(),当数据准备就绪时,缓存实际值.高速缓存检索将检查实际数据并执行Observable.just或返回待处理的Observable或发起新请求.
缓存replay(1).autoConnect(1)并始终返回
后者似乎更直接,但它有一个警告,如何在缓存必须无效时正确处置observable.
签名有:
public Observable<T> autoConnect(int numberOfSubscribers, Consumer<? super Disposable> connection)
但很难说我如何跟踪未完成的订阅以及处理是否优雅.
前者将负责资源释放,但你必须产生更复杂的逻辑.
为什么不.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);}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
603 次 |
| 最近记录: |