Last active
November 27, 2017 00:41
-
-
Save satoshun/39b08e587a209c4b64ee342bf07e0bf9 to your computer and use it in GitHub Desktop.
Kotlin and RxJava Cacheのコード part1
This file contains hidden or 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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
引数の数が増えたらTuple2, 3, ... Nと際限なく増えていくのでここをなんとかしたい