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

amar_1995

08/23/2020, 2:10 PM
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

Adam Powell

08/23/2020, 2:58 PM
What have you tried so far?
a

amar_1995

08/23/2020, 3:31 PM
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

Zach Klippenstein (he/him) [MOD]

08/23/2020, 4:14 PM
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

Adam Powell

08/23/2020, 4:17 PM
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

amar_1995

08/23/2020, 9:06 PM
So that means
Providers
will only work for children but we can't return data from providers in parent node of a tree ?
a

Adam Powell

08/23/2020, 11:55 PM
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
2 Views