Created
January 30, 2017 17:58
-
-
Save anonymous/279014b6e4313c360b86812cbbf3ec3c to your computer and use it in GitHub Desktop.
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
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