vaskir
06/04/2020, 9:09 AMfun <T> (suspend () -> T).memoize() : suspend () -> T {
var value: T? = null
return suspend { value ?: this().also { value = it }}
}
suspend fun work() : Int = coroutineScope {
delay(1000)
22
}
val memoizedWork = ::work.memoize()
elizarov
06/04/2020, 9:52 AMvalue
when memoized function is called concurrently.elizarov
06/04/2020, 9:54 AMelizarov
06/04/2020, 9:55 AMelizarov
06/04/2020, 9:58 AMval memoized = scope.async(start = CoroutineStart.LAZY) { work() }
// when you need its value:
memoized.await()
vaskir
06/04/2020, 10:31 AMvaskir
06/04/2020, 10:34 AMsuspend lazy val ...
would be nice to have though 😉gildor
06/04/2020, 3:45 PMoctylFractal
06/04/2020, 5:01 PMscope.lazy {}
, which is probably as close as it would ever getgildor
06/05/2020, 1:49 AMval memoizedWork = lazy { work() }
Marc Knaup
07/10/2020, 4:02 PMsuspend val
with lazy
would be nice!
I just ran into the same issue.
I’d need a coroutine scope to initialize a property val
with .async
- but I don’t have one when initializing members.
I’d like to use the scope of the first access to the property instead 🤔