spand
04/15/2021, 6:19 AMclass SuspendAtomicRef<T : Any> {
private var data: T? = null
private val mutex = Mutex()
suspend fun getOrSet(init: suspend () -> T): T {
return mutex.withLock {
data ?: init().also { data = it }
}
}
}
Seems pretty basic so I wonder if I am missing it in the coroutines library?Dominaezzz
04/15/2021, 7:44 AMspand
04/15/2021, 7:51 AMinit
invocations the entire point of itDominaezzz
04/15/2021, 7:53 AMephemient
04/15/2021, 1:13 PMspand
04/16/2021, 5:01 AMSuspendAtomicRef
work better in that:
1. Needs no coroutine on allocation (great for properties)
2. Supports cancellation much better in that a cancelled init
will not break or block the others waiting.