Skip to content

Instantly share code, notes, and snippets.

@satoshun
Last active November 27, 2017 00:41
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 satoshun/39b08e587a209c4b64ee342bf07e0bf9 to your computer and use it in GitHub Desktop.
Save satoshun/39b08e587a209c4b64ee342bf07e0bf9 to your computer and use it in GitHub Desktop.
Kotlin and RxJava Cacheのコード part1
class UserRepository(
userDao: UserDao
) {
private val userDaoWithCache = Cache(userDao::getUser)
fun getUser(id: Int, name: String): Single<User> {
return userDaoWithCache.fetchOrCache(id, name)
}
}
class Cache<K1, K2, V>(
private val invoker: (K1, K2) -> Single<V>
) {
private val cache = HashMap<Tuple2<K1, K2>, V>()
fun fetchOrCache(key1: K1, key2: K2): Single<V> {
val key = Tuple2(key1, key2)
val value = cache[key] ?: return invoker(key1, key2).doOnSuccess { cache[key] = it }
return Single.just(value)
}
}
data class Tuple2<out V1, out V2>(val v1: V1, val v2: V2)
class UserDao {
fun getUser(id: Int, name: String): Single<User> {
return Single.just(User(id, name))
.delay(500, TimeUnit.MILLISECONDS)
}
}
data class User(val id: Int, val name: String)
@satoshun
Copy link
Author

引数の数が増えたらTuple2, 3, ... Nと際限なく増えていくのでここをなんとかしたい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment