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

Manuel Wrage

01/10/2020, 10:27 AM
Can we expect some ambient functions like 'ambientOrNull' or 'ambientOrElse'?
a

Adam Powell

01/10/2020, 2:09 PM
I think we're pushing more for a world where ambients carry their own default so that there's no such thing as one that's unset. In that world you could build what you're asking about using your own sentinel if you really wanted, but the API design implications are not much fun.
Ambients already carry a risk in that you never know what ambients a composable function might read as implementation details when you call it
It's almost always better to pass params explicitly when you can; ambients are for when something is cross-cutting or otherwise too cumbersome
The ambients consumed by a whole subtree are in effect part of the API surface of every composable that calls a composable that reads the ambient
It gets hard to reason about quick
Even more so if the same ambient can have very different default behavior from consumer to consumer
There will be cases where it comes up and there's not a clearly better alternative for sure, but I suspect it's not worth a series of convenience APIs to optimize or encourage that case.
Please give us examples of cases where you want this when you encounter them to build a case for them though 🙂
a

alexsullivan114

01/10/2020, 2:34 PM
I like the idea of default ambients. If I'm not mistaken, the theming engine works via ambients right? I think it's a really powerful tool with a large tradeoff in how easy it is to reason about a composable. Was it inspired by the context API in React? It feels similar but somehow a bit more powerful.
If there's no default ambients then I think I like the idea of some way to get a nullable ambient. The problem is that ambients just fundamentally make your composables like, non deterministic and deeply coupled with something else
a

Adam Powell

01/10/2020, 4:26 PM
yeah it's the same idea, but
Context
is very much a taken name on android 😄
so read any of your favorite, "react context considered harmful" posts and they'll apply here too
I hesitate to call what we're doing in compose material so far a, "theming engine" - it's just using some ambients for some very generalized UI attributes
it's that sort of use case where I think things like ambients shine - it's very possible to define default values for those ambients and have things be useful if you forget about them
👍 1
or getting access to an android
Context
for loading resources or launching activities or binding services or whatnot, where you really don't want people capturing uncontrolled references and you'd like it to change and recompose if you cross an activity recreation or something, but if it's not present at all the only reasonable thing to do is probably crash
👌 1