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

Daniele B

09/14/2020, 3:53 PM
I also had the idea of using
ambientOf
in this way, which is basically the same way you would use
@EnvironmentObject
in SwiftUI: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1592352556316500
Copy code
@Composable
fun foo(appState: StateFlow<ChannelState>) {
  val currState by appState.collectAsState()
  Providers(CurrAppState provides currState) {
    // Content that should see currState
  }
}
as a kind of “dependency injection”, which “saves” an object in the environment, so that it’s possible to call it down the tree without having it passed all the time as a parameter. But I didn’t understand the explanation of @Adam Powell and @Zach Klippenstein (he/him) [MOD] why
ambientOf
should not be used in this use case, and what is the way to use it instead.
a

Adam Powell

09/14/2020, 5:45 PM
Mechanically it works, but the implicit dependency it creates will make things more cumbersome to use, reuse, test, and reason about. Semantically speaking you probably want to split out individual sub-pieces of state that each composable consumes via parameters as you descend down the tree rather than having the whole app state everywhere, which makes this pattern of ambient usage less useful.
d

Daniele B

09/14/2020, 5:54 PM
So, I guess JetpackCompose is not promoting the same concept of
@EnvironmentObject
on SwiftUI
@Adam Powell so if
ambientOf
is not to be used to have an environment object like in
@EnvironmentObject
, what is it for and how should it be used?
a

Adam Powell

09/14/2020, 6:25 PM
It can certainly be used that way mechanically, it's more of a question of design and best practice. It should be used when those kinds of implicit dependencies are situationally appropriate, which I realize is a circular and unsatisfying answer. 🙂 Theming constructs are one example where the tradeoffs tend to be worth the potential for confusion, along with other information like density scaling
Much of the advice given for react's context feature applies here: https://reactjs.org/docs/context.html#before-you-use-context
if you would feel strange using a
ThreadLocal
to get information into a regular function call as opposed to via parameter passing, you should similarly feel strange about using ambients to provide information to composable function calls
📌 2
sometimes it's an appropriate and elegant solution to a problem; other times it's hiding things that should probably remain visible and explicit
s

Sean McQuillan [G]

09/14/2020, 6:34 PM
Agreed with Adam. Personally my current rule for ambient vs. parameter goes something like this: "Ambients should be reserved for select foundational app-wide or ecosystem-wide architectural pieces, everything else is parameters"
d

Daniele B

09/14/2020, 6:39 PM
@Adam Powell thanks! I get the point now
5 Views