Skip to content

Instantly share code, notes, and snippets.

@mrmitew
Created October 6, 2017 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrmitew/84148d02ff360d2749013a250b23a15d to your computer and use it in GitHub Desktop.
Save mrmitew/84148d02ff360d2749013a250b23a15d to your computer and use it in GitHub Desktop.
Caching of observables for inflight requests
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