It's okay to use launched effects to navigate when...
# compose
l
It's okay to use launched effects to navigate when a state changes? For example, a login view:
Copy code
val isLoginError by loginViewModel.loginError.observeAsState()
    val context = LocalContext.current
    LaunchedEffect(isLoginError){
        when (isLoginError) {
            true -> {
                Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
            }
            false -> navHostController.navigate(Paths.HOME_PATH)
            null -> { // blah }
        }
    }
    LoginScreen(loginViewModel)
j
That seems Ok. I’ve handled this sort of thing in my app by injecting a shared Navigation flow into my VMs. I can then emit Navigation directions to that flow directly from the VM which is collected at a global level and then the global collector calls navHostController as appropriate.
🙌 1
l
Can you share your solution? that looks like an interesting approach
j
To be fair, I didn’t come up with it. I think I found the idea in this article: https://proandroiddev.com/jetpack-compose-navigation-architecture-with-viewmodels-1de467f19e1c
He shows a good example and explains why about halfway down the article.
So we can thank @Syex for this one. 🙏
it’s worked out great for testability and very easy to use within our application.
s
You're welcome 🙂
l
Thanks! I'll look into that 😄