I’m having some issues with navigation in compose ...
# compose
l
I’m having some issues with navigation in compose and state handling with it. Code in thread
I created a NavHost like this
Copy code
val navController = rememberNavController()

NavHost(navController = navController, startDestination = "mainpicker") {
    composable("mainpicker") {
        ContactPickerScreen(
            viewModel = viewModel,
            onClientClicked = { viewModel.onAction(Action.ClientPressed) }
        )
    }
    composable("myclients") { MyClientsScreen() }
}
the MainPicker screen is a simple composable that shows multiple rows to select different types of contacts (Clients, Phone Contacts, Friends, etc)
and that works fine if I handle the navigation directly from the composable (i.e calling
navController.navigate("myclients")
in the
onClientClicked
callback
but I’m trying to move the state to the viewmodel. So I created a simple enum that holds each screen’s route, and I’m exposing that from the viewmodel as a
StateFlow
Which brings me to the issue that I’m having. What is the correct way of observing the navigation state from the viewmodel?
I tried doing
val model by viewModel.state.collectAsState()
but then I’m not sure where to add the
navController.navigate(model.route)
. I tried adding it at the bottom of the composable like:
Copy code
val model by viewModel.state.collectAsState()
                        val navController = rememberNavController()

                        NavHost(navController = navController, startDestination = "mainpicker") {
                            composable("mainpicker") {
                                ContactPickerScreen(
                                    viewModel = viewModel,
                                    onClientClicked = { viewModel.onAction(Action.ClientPressed) }
                                )
                            }
                            composable("myclients") { MyClientsScreen() }
                        }

                        navController.navigate(model.route)
which gives me a crash, and I’m pretty sure it is wrong? And help is appreciated 🙏
i
You should never be calling imperative code (i.e.,
navigate()
) as part of composition, that's never correct
There's quite a few threads about collecting events in Compose that you can use for navigation events, such as the one from yesterday: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1622555319061500?thread_ts=1622550102.030800&cid=CJLTWPH7S
👍🏽 1
👍 2
l
thanks! I had a feeling just calling
navigate()
in the composition was wrong. I’ll take a look at that thread