Is it stupid idea to create `CompositionLocalProvi...
# compose
j
Is it stupid idea to create
CompositionLocalProvider
that provides navcontroller so that i do not need to pass navcontroller from parent down to child composable?
f
That adds a hidden dependency that would complicate usage of your composables, as well as previewing and testing them.
You shouldn't pass the navController for these same reasons and instead use lambdas
j
hmm https://stackoverflow.com/questions/70614765/jetpack-compose-how-to-centralize-navcontroller-and-inject-it i read this and it seems it should be fine. why this is actually complicated ?
f
Sure you can do it that way if you want, it's just not recommended and likely to bite you in the rear end, but only you can decide what's best for your app.
j
I do not want to use it everywhere have on very specific case when I have some kind of server side rendering and I have composables for example TileListView that is generic component and it should not know anything about navigation nor about function that deep down child should execute to run navigation. I though maybe for those use cases I can still use it
f
you just describe the exact reason why you shouldn't do it:
it should not know anything about navigation
by adding a local composition that provides the navigation you are now having this dependency and having your comopsables know about navigation. The recommendation is to have lambdas that are called when the user initiates some action, and up in your root composable, in the navigation graph, those actions trigger a navigation event. The composable does not need to know what the user action ends up triggering, its only responsibility is to push that event up the chain to the point where it can be actioned
j
haha good one!
c
state down events up pass a lambda into where you need it and your composables become infinitely more testable.
j
Just to restate, we also have this in our docs:
We strongly recommended that you decouple the Navigation code from your composable destinations to enable testing each composable in isolation, separate from the
NavHost
composable.
I wrote a full explanation on how/why a while ago: https://medium.com/google-developer-experts/navigating-in-jetpack-compose-78c78d365c6a