假设简化的类如下:
class MyModel() {
companion object
val number = mutableStateOf(0)
init {
refresh()
}
fun refresh() {
RestClient.getNumber()
.doOnNext { i ->
number.value = i
}
.take(1)
.subscribe()
}
}
我在其他地方实例化了它:
val myModel = remember {
MyModel()
}
有时我会得到:
原因:java.lang.IllegalStateException:读取状态 在拍摄快照后或尚未拍摄的快照中创建 已申请于 androidx.compose.runtime.snapshots.SnapshotKt.readError(Snapshot.kt:1865) 在 androidx.compose.runtime.snapshots.SnapshotKt.current(Snapshot.kt:2171) 在 androidx.compose.runtime.SnapshotMutableStateImpl.setValue(SnapshotState.kt:299) 在 com.example.MyModel$refresh$4.accept(MyModel.kt:14)
如何避免提及
IllegalStateException
?
您遇到的非法状态异常可能是由于并发问题引起的,为了避免此问题,您应该确保以与 compose 生命周期兼容的方式执行状态更新。
class MyModel : ViewModel() {
val number by mutableStateOf(0)
init {
refresh()
}
fun refresh() {
viewModelScope.launch(Dispatchers.IO) {
val newNumber = RestClient.getNumber()
// Update the state on the UI thread
viewModelScope.launch(Dispatchers.Main) {
number.value = newNumber
}
}
}
}