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
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: