Is there something like dependency injection or BL...
# compose
t
Is there something like dependency injection or BLOC or environmental object?
j
Yes, search aosp for references to
Ambient
, but please be super careful and use it very sparingly. It is quite dangerous in the sense that it isn't statically checked and can very quickly make your apps a maintainability nightmare.
f
How are you supposed to use it then?
j
My answer is: don't. But if you feel you must, then use it sparingly and only for things where passing the value as a parameter would be prohibitively burdensome. There are some valid use cases, like specifying the current locale for text, but more often than not, they are abused by new users.
f
What is the recommended way to handle state without passing it throughout the entire app then?
I think this is the main question @Tristan Caron is asking
j
The recommendation is to pass state explicitly as parameters to your composable functions. It feels a bit annoying at first, but you soon realize it's not so bad, and keeps your code readable+maintainable.
👍 1
2
t
So how would you handle this scenario?
Copy code
Page(user = user, avatarSize = avatarSize)
// ... which renders ...
PageLayout(user = user, avatarSize = avatarSize)
// ... which renders ...
NavigationBar(user = user, avatarSize = avatarSize)
// ... which renders ...
Link(href = user.permalink) {
  Avatar(user = user, size = avatarSize)
}
f
Hmm. Interesting. In Flutter/React you have all of these paradigms that Tristan mentioned, in addition to redux and MobX.
👆 1
j
Yeah, if you're truly implementing redux/mobx, that might be a valid reason to use ambients.
PageLayout
probably shouldn't have access to user and avatarSize; it should just do layout and the children should capture the values lexically. Probably same is true of
NavigationBar
, depending on your implementation. Often, users claim they need to plumb parameters through every intermediate widget, but when they go to implement it, realize that lexical scoping often allows you to jump across levels.
w
Jim, do you mean you’d rather see
fun PageLayout(navigationBar: @Compose() () -> Unit, content: @Composable() () -> Unit
? And then navigationBar child can be
fun NavigationBar(leading: @Composable() () -> Unit, items...
etc.? And then most of the time you’ll pass things just one-two levels down at most?
g
Jim: "Here's that nuclear hand grenade you asked for." Dev: "Great! How do I use it?" Jim: "Don't, but if you do, be careful, it will blow you up." Dev: "So what's it good for?" Jim: "It blows stuff up! It is great for clearing large areas of land. I hope you can run fast or even better, drop it from a low-flying airplane."
❤️ 3
👍 1
🤣 7
j
@wasyl Yes, exactly. @George Mount Yes, exactly. 😂🤣