Sam Stone
07/14/2023, 12:38 PMsynchronized
on KMM. How do I translate this to KMM?
/**
* Analog of val prop by lazy {}
that allows mutability (i.e. var
by LazyMutable {}
)
* https://stackoverflow.com/a/47948047/12528345
* */
class LazyMutable<T>(val initializer: () -> T) : ReadWriteProperty<Any?, T> {
private object UNINITIALIZED_VALUE
private var prop: Any? = UNINITIALIZED_VALUE
@OptIn(InternalCoroutinesApi::class)
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return if (prop == UNINITIALIZED_VALUE) {
synchronized(this) {
return if (prop == UNINITIALIZED_VALUE) initializer().also { prop = it } else prop as T
}
} else prop as T
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
synchronized(this) {
prop = value
}
}
}
mbonnin
07/14/2023, 12:41 PMVidmantas Kerbelis
07/14/2023, 1:13 PMprivate val mutex = Mutex()
mutex.withLock { }
runBlocking { mutex.withLock { } } // Maybe an option, I can't guarantee that this is a good approach