Created
October 6, 2017 10:44
-
-
Save mrmitew/84148d02ff360d2749013a250b23a15d to your computer and use it in GitHub Desktop.
Caching of observables for inflight requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReactiveCache<in K, V>(private val generator: Function<K, Observable<V>>) { | |
private val requests: MutableMap<K, ConnectableObservable<V>> = HashMap() | |
@Throws(Exception::class) | |
operator fun get(key: K): Observable<V> { | |
var result: ConnectableObservable<V> = Observable.empty<V>().replay() | |
synchronized(requests) { | |
val current = requests[key] | |
if (current != null) { | |
return current | |
} | |
result = generator.apply(key) | |
.doOnTerminate { | |
synchronized(requests) { | |
requests.remove(key) | |
} | |
} | |
.replay() | |
requests.put(key, result) | |
} | |
return result.autoConnect(0) | |
} | |
fun clear() { | |
synchronized(requests) { | |
requests.clear() | |
} | |
} | |
fun clear(key: K) { | |
synchronized(requests) { | |
requests.remove(key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment