[BUG] ViewModel onCleared never called and viewModelScope is never cancelled
LittleTrickster opened this issue · comments
Vladas Maksimkinas commented
Describe the bug
ViewModel onCleared never called and viewModelScope is never cancelled
Minimal reproducible example
It is Desktop
@Composable
fun App() {
var show by remember { mutableStateOf(false) }
Button(onClick = {
show = !show
}) {
Text("show $show")
}
if (show) {
Test1()
}
}
class TestViewModel : ViewModel() {
init {
println("init")
}
override fun onCleared() {
println("onCleared")
}
}
@Composable
fun Test1() {
val viewModel = viewModel { TestViewModel() }
}
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
PreComposeApp {
App()
}
}
}
Tlaster commented
The lifecycle of the ViewModel is bound to a StateHolder
, in this case the root StateHolder
is used, which is inside PreComposeApp
, the lifecycle of the root StateHolder
lives as long as the application is running, so onCleared
is never called when you click the button, which is the expected behavior.
Vladas Maksimkinas commented
Thanks.
Sad that it is not the same like on android but if it is intended behavior I'll move on. At least I'm happy navigation is working.