Created
November 28, 2017 00:54
-
-
Save satoshun/21cb24efb287d921468d14b2708b205a to your computer and use it in GitHub Desktop.
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 UserRepository2( | |
userDao: UserDao | |
) { | |
private val userDaoWithCache = Cache2(userDao::getUser) | |
private val userDao2WithCache = Cache2(userDao::getUser2) | |
fun getUser(id: Int, name: String): Single<User> = | |
userDaoWithCache(id, name) | |
fun getUser2(id: Int, name: String, password: String): Single<User> = | |
userDao2WithCache(id, name, password) | |
} | |
class UserDao { | |
fun getUser(id: Int, name: String): Single<User> { | |
return Single.just(User(id, name)) | |
.delay(500, TimeUnit.MILLISECONDS) | |
} | |
fun getUser2(id: Int, name: String, password: String): Single<User> { | |
if (password.isEmpty()) return Single.error(Exception()) | |
return Single.just(User(id, name)) | |
.delay(500, TimeUnit.MILLISECONDS) | |
} | |
} | |
data class User(val id: Int, val name: String) | |
class Cache2<R>( | |
private val invoker: Function<Single<R>> | |
) { | |
private val cache = HashMap<Int, R>() | |
operator fun invoke(vararg args: Any): Single<R> { | |
val key = hashCode(args) | |
cache[key]?.let { | |
return Single.just(it) | |
} | |
return ((invoker as? Function1<Any, Single<R>>)?.invoke(args[0]) | |
?: (invoker as? Function2<Any, Any, Single<R>>)?.invoke(args[0], args[1]) | |
?: (invoker as? Function3<Any, Any, Any, Single<R>>)?.invoke(args[0], args[1], args[2]) | |
?: throw IllegalArgumentException("no much Function type") | |
).doOnSuccess { cache[key] = it } | |
} | |
// todo it's wrong hashcode | |
private fun hashCode(args: Array<out Any>): Int = args.sumBy { it.hashCode() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment