InvalidMutabilityException on IOS with mutable variables using coroutines in Kotlin Multiplatform
Asked Answered
S

1

5

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

Smith answered 16/12, 2020 at 18:30 Comment(0)
I
10

Kotlin/Native has a different threading model than the JVM. TestClass gets frozen when the data is captured in the lambda. The string assignment silently captures the parent TestClass and freezes it.

See the following:

Irfan answered 16/12, 2020 at 18:42 Comment(1)
Awesome talk of Kevin Galligan! Helped a lot! ThanksSmith

© 2022 - 2024 — McMap. All rights reserved.