Search code examples
kotlingetter-setterkotlin-coroutines

how to write getter and setter containing mutex.withLock in kotlin


I'd like to have a synchronised access to a variable that represents my state from coroutines. How can I fix this?

private var myState: MyState? = null
    get() = mutex.withLock {
        return@withLock myState
    }
    set(value) = mutex.withLock {
        field = value
    }
private val mutex = Mutex()    

right now I get Suspend function 'withLock' should be called only from a coroutine or another suspend function message. If not possible any alternative elegant solutions?


Solution

  • To call suspend function in a non-suspending context. You can use runBlocking.

    private var myState: MyState? = null
        get() {
            return runBlocking {
                mutex.withLock {
                    myState
                }
            }
        }
        set(value) {
            runBlocking {
                mutex.withLock {
                    field = value
                }
            }
        }
    private val mutex = Mutex()    
    

    NOTES:

    You might be better off changing the property to two suspend functions (getter/setter), instead of using runBlocking. All depends on the context in which you call myState.

    You also want to consider voting for KT-15555.