https://kotlinlang.org logo
Title
j

Jan Skrasek

08/30/2021, 7:21 AM
Why is not NavController a local? I'd love to use ~ findNavController() instead of creating callbacks for every action/or passing the NavController down.
f

Felix Schütz

08/30/2021, 7:45 AM
Just use your own
CompositionLocal
(https://developer.android.com/reference/kotlin/androidx/compose/runtime/CompositionLocal). But components lower down should probably not depend on the nav controller, since that makes testing more difficult.
👆 2
f

Filip Wiesner

08/30/2021, 8:17 AM
Agreed, you should always think twice about introducing
CompositionLocals
to your project because they are a "hidden dependency" of sorts that makes it hard to reuse the components that depend on it.
☝️ 1
👍 1
j

Jan Skrasek

08/30/2021, 8:22 AM
Majority of composable functions (their LOC) is not reusable... Yes, it make sense to make it explicit, though we already are taught to do it properly with state hoisting (and VMs, etc.), no reason we couldn't design this correctly too. I believe this is not strong enough argument not to have it, but understand others feel differently.
f

Filip Wiesner

08/30/2021, 8:32 AM
I didn't say you shouldn't use it, only to think twice about using it. If you are going to use it like in the view-system and call ~findNavController() only in "big" components (fragments) at the top of the tree, it should be fine. The thing about
CompositionLocals
is that you can access them even in the leaf nodes of your tree like a button so it makes it easy to use it "wrongly". And if you use the nav controller only on top of your tree, then it's not that hard to just pass a lambda 😄 Hope it makes sense
👍 1
i

Ian Lake

08/30/2021, 2:48 PM
This is precisely the anti-thesis for making reusable, testable components, which is why we specifically chose not to provide one. See our testing guide for how you should be separating your code from any dependency on a Navigation system: https://developer.android.com/jetpack/compose/navigation#testing
2
j

jossiwolf

08/30/2021, 5:54 PM
Refactoring nav logic that is scattered across 80 Composables also is a pain in the ass... been there done that. Hoist & co-locate your nav! (shameless plug, I wrote a post that also covers this: https://medium.com/google-developer-experts/navigating-in-jetpack-compose-78c78d365c6a)
👍 4