Skip to content

Instantly share code, notes, and snippets.

Created January 30, 2017 17:58
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 anonymous/279014b6e4313c360b86812cbbf3ec3c to your computer and use it in GitHub Desktop.
Save anonymous/279014b6e4313c360b86812cbbf3ec3c to your computer and use it in GitHub Desktop.
import rx.Single
class RamCache<in K, V>(val factory: (K) -> Single<V>): (K) -> Single<V> {
private val cache: MutableMap<K, V> = mutableMapOf()
private val requests: MutableMap<K, Single<V>> = mutableMapOf()
fun clear() {
cache.clear()
requests.clear()
}
override fun invoke(key: K): Single<V> {
val c = cache[key]
return if (c != null)
Single.just(c)
else {
if (requests[key] != null) {
requests[key]!!
} else {
factory(key)
.apply {
requests[key] = this
}
.doOnSuccess {
cache[key] = it
requests.remove(key)
}
.doOnError {
requests.remove(key)
}
.doOnUnsubscribe {
requests.remove(key)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment