hey guys, i'm confusing about whether it is appropriate to provide
NavController
in the form of
CompositionLocal
?
y
yschimke
10/09/2022, 9:19 AM
I tried this and got advised to move away from it. I ended up with a top level App composable, that sets up navigation routes, but also creates lambdas to pass into each individual screen. It's really easy to overuse CompositionLocal but ultimately I felt it made the code cleaner, as I could leave the navigation logic in one place.
y
Young Rock
10/09/2022, 9:28 AM
Thanks for your experience sharing, the problem I'm facing is that at the top composable screen, I need to write a lot of navigation events params like
onClickXxx
which are flowed up by child composable, that make the top screen's code full of navigation logic.
y
yschimke
10/09/2022, 9:44 AM
You could funnel them through a single navigation lambda taking a destination. But wait for advice for others. I only have a few per screen
n
nlindberg
10/09/2022, 10:16 AM
I ususally configure the viewmodel of the composable that sets up the navigation graph with the controller and then pass the viewmodel or an interface to it that does navigation. Not sure if there are any downsides to it 🤷
E.g.
Copy code
val contentController = rememberAnimatedNavController()
mainViewModel.configure(contentController)
val starRoute = mainViewModel.startRoute()
where NavigationActions is an interface on mainviewmodel.
Copy code
override fun navigate(screen: ContentScreen) {
viewModelScope.launch {
val current = contentController?.currentDestination?.route
if (current != screen.route) contentController?.navigate(screen.route)
}
}
y
yschimke
10/09/2022, 10:39 AM
I thought viewmodels shouldn't hold any references to activity or navigation controller. To avoid leaks?
n
nlindberg
10/09/2022, 10:42 AM
Yeah could be, but the code looks cleaner, still have it on my todo to check if it leaks :d