Tlaster / PreCompose

Compose Multiplatform Navigation && State Management

Home Page:https://tlaster.github.io/PreCompose/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[BUG] ViewModel onCleared never called and viewModelScope is never cancelled

LittleTrickster opened this issue · comments

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()
        }
    }
}

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.

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.