Timo Drick
08/28/2025, 11:36 AMclass TestViewModel(ctx: Application): AndroidViewModel(ctx) {
var value by mutableStateOf("Start")
init {
value = "Init"
viewModelScope.launch(Dispatchers.IO) {
value = "Loaded"
}
}
}
@Composable
fun Test(vm: TestViewModel = viewModel()) {
Text(vm.value)
}
When i change the init to:
init {
value = "Initialized"
viewModelScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
value = "Loaded"
}
}
}
It shows "Loaded"
Also a delay would make the code work.
Normally i think changing a compose state variable it is not necessary to be on the UI ThreadZach Klippenstein (he/him) [MOD]
08/28/2025, 7:08 PMvalue
state object has been applied so as far as that coroutine is concerned the state doesn't exist yet. There are two things that would likely work here.
Probably the better option, since it's good practice for other reasons, is to perform state mutations on a background thread in an explicit snapshot:
value = "Init"
viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
Snapshot.withMutableSnapshot {
value = "Loaded"
}
}
This is nice since it also handles updating multiple states from that coroutine and ensures the updates are all published together at the same time.
Another option is to explicitly tell the snapshot system after your states are initialized:
value = "Init"
Snapshot.notifyObjectsInitialized()
viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
value = "Loaded"
}
This doesn't handle updating multiple states from a background thread though.Timo Drick
08/29/2025, 9:26 AMTimo Drick
08/29/2025, 9:26 AMTimo Drick
08/29/2025, 9:26 AMTimo Drick
08/29/2025, 9:30 AMAlbert Chang
08/29/2025, 10:50 AMmutableStateOf
in composition but try to update it in background thread before the composition is completed, the update won't succeed. This is kind of expected due to how the snapshot system works.
This used to result in an exception in older compose versions: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1652084646064769
Now there won't be a crash but as I said the update won't work.Zach Klippenstein (he/him) [MOD]
08/29/2025, 5:39 PM