IOS上的InvalidMutabilityException使用Kotlin Multiplatform中的协程,具有可变变量
我简化了错误,我只有这个类:IOS上的InvalidMutabilityException使用Kotlin Multiplatform中的协程,具有可变变量,kotlin,kotlin-coroutines,kotlin-multiplatform,kotlin-native,Kotlin,Kotlin Coroutines,Kotlin Multiplatform,Kotlin Native,我简化了错误,我只有这个类: class TestClass{ private var string = "Hello" fun testError() { string= "It Works" GlobalScope.launch(Dispatchers.Default) { string = "Doesn't work" } } }
class TestClass{
private var string = "Hello"
fun testError() {
string= "It Works"
GlobalScope.launch(Dispatchers.Default) {
string = "Doesn't work"
}
}
}
如果我在主线程(在IOS上)上启动TestClass().testError(),它将抛出InvalidMutabilityException(在-->string=“不工作”行)。所以我想,除了创建变量的线程外,在其他线程上更改变量可能不是一个好主意。所以我改为:
class TestClass{
private var string = "Hello"
fun testError() {
string= "It Works"
GlobalScope.launch(Dispatchers.Default) {
withContext(Dispatchers.Main) { string = "Doesn't work" }
}
}
}
但它仍然抛出了一个错误:
kotlin.native.concurrent.InvalidMutabilityException:冻结的com.example.project的突变尝试。TestClass@fe10a8
顺便说一下。上述两个代码都在Android端工作,Kotlin/Native的线程模型与JVM不同<代码>测试类在lambda中捕获数据时被冻结。
字符串
赋值以静默方式捕获父级TestClass
并将其冻结
见下文: