https://kotlinlang.org logo
#compose
Title
# compose
j

Jasmin Fajkic

08/21/2022, 4:52 PM
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

Francesc

08/21/2022, 5:08 PM
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

Jasmin Fajkic

08/21/2022, 5:11 PM
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

Francesc

08/21/2022, 5:16 PM
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

Jasmin Fajkic

08/21/2022, 5:31 PM
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

Francesc

08/21/2022, 5:35 PM
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

Jasmin Fajkic

08/21/2022, 8:40 PM
haha good one!
c

Colton Idle

08/22/2022, 3:51 AM
state down events up pass a lambda into where you need it and your composables become infinitely more testable.
j

jossiwolf

08/22/2022, 10:16 AM
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
36 Views