Skip to content

Instantly share code, notes, and snippets.

@satoshun
Created November 28, 2017 00:54
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/21cb24efb287d921468d14b2708b205a to your computer and use it in GitHub Desktop.
Save satoshun/21cb24efb287d921468d14b2708b205a to your computer and use it in GitHub Desktop.
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