Derek Berner
08/06/2019, 7:25 PMimport kotlinx.coroutines.*
@JvmName("_memoize_receiver")
fun <T,R> (suspend (T) -> R).memoize(): suspend (T) -> R {
val memos = mutableMapOf<T, Deferred<R>>()
val f = this
return { t ->
coroutineScope {
withContext(coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>) {
synchronized(memos) {
memos.computeIfAbsent(t) { async { f(t) } }
}
}.await()
}
}
}
fun <T,R> memoize(f: suspend (T) -> R): suspend (T) -> R = f.memoize()
jw
08/06/2019, 7:26 PMDerek Berner
08/06/2019, 7:28 PMIO
seems bad, where avoidableyschimke
08/07/2019, 6:05 AMAntanas A.
08/07/2019, 7:13 AMsuspend inline fun <R> (suspend () -> R).memoize(): suspend () -> R {
val Undef = object {}
var value: Any? = Undef
return suspend {
if (value === Undef) value = this() as Any?
value as R
}
}