InvalidMutabilityException on IOS with mutable variables using coroutines in Kotlin Multiplatform

Viewed 1185

I simplified the error, and I just have this class:

class TestClass{
    private var string = "Hello"

    fun testError() {
        string= "It Works"
        GlobalScope.launch(Dispatchers.Default) {
            string = "Doesn't work"
        }
    }
}

If I launch TestClass().testError() on the main thread (on IOS), it throws an InvalidMutabilityException (at line --> string = "Doesn't work"). So I thought that maybe it's not a good idea to change the variable on a thread other than the one that created the variable. So I changed to this:

class TestClass{
    private var string = "Hello"

    fun testError() {
        string= "It Works"
        GlobalScope.launch(Dispatchers.Default) {
            withContext(Dispatchers.Main) { string = "Doesn't work" }
        }
    }
}

but it still throws an error:

kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen com.example.project.TestClass@fe10a8

By the way. Both codes above work on Android side

1 Answers
Related