Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
LittleTrickster opened this issue Mar 29, 2024 · 2 comments

Comments

@LittleTrickster
Copy link

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
Copy link
Owner

Tlaster commented Mar 29, 2024

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.

@LittleTrickster
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants