I am trying to use `ProvidableAmbient` to pass da...
# compose
a
I am trying to use
ProvidableAmbient
to pass data from screen1 to screen2. How to update data in screen2 and return back to screen1 ?
a
What have you tried so far?
a
I have tried to first pass to the data in screen2 but I am unable to update data. I tried using
provides()
and
provides
to update the value but
z
Providers
associates a value with an ambient only for children of the
Providers
composable. It doesn’t affect code above, before, or after itself. If
screen1
and
screen2
are siblings, how are you using ambients to communicate between them? The only way I could see that working is if a parent composable of both screens provided the same ambient value to both, and that value was some sort of mutable object (perhaps a
MutableState
) that each screen could observe and mutate independently.
a
yes,
provides
in a
Providers(...) { }
call works like
to
in
mapOf(...)
it works like
Copy code
Providers(foo provides bar) {
  if (foo.current == bar) // this will be true
just as
Copy code
val myMap = mapOf(foo to bar)
if (myMap[foo] == bar) // this will be true
ambients are keys into a composition-local persistent (in the persistent data structure sense) map.
if you would like screen2 to be able to edit data that screen1 can see, it might conceptually look something like this:
Copy code
val sharedState = remember ( MyState() }
when (sharedState.currentScreen) {
  Screens.One -> Screen1(sharedState)
  Screens.Two -> Screen2(sharedState)
}
and then
MyState
would offer an API that Screen1 and Screen2 can use
using ambients here is likely not what you want, as you're creating hidden dependencies and requirements that are harder to reason about
a
So that means
Providers
will only work for children but we can't return data from providers in parent node of a tree ?
a
Correct. You can provide a mutable object that other things can observe changes to but that's the most you can do in this regard. Ambients don't change the top down ownership of data, they only allow you to provide data implicitly