class 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?
d
Dominaezzz
04/15/2021, 7:44 AM
Odd, why not just use an atomic ref? Would be faster.
s
spand
04/15/2021, 7:51 AM
It for an optimization so reducing multiple
init
invocations the entire point of it
d
Dominaezzz
04/15/2021, 7:53 AM
Ah, I missed the init part.
Dominaezzz
04/15/2021, 7:55 AM
Given you still hit the mutex even after initialisation, there's still much room for improvement.
Dominaezzz
04/15/2021, 7:55 AM
I also feel like I would refactor my code to not need this but that's probably just ignorance due to lack of use case.