There is no `synchronized` on KMM. How do I translate this to KMM? /** * Analog of `val prop by la...
s
There is no
synchronized
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 * */
Copy code
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
        }
    }
}
m
I've used atomicfu successfully before
v
You could use a mutex (if you’re in a suspend function):
Copy code
private val mutex = Mutex()
mutex.withLock { }

runBlocking { mutex.withLock { } } // Maybe an option, I can't guarantee that this is a good approach