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

spierce7

02/12/2021, 10:54 PM
Can Ambients be used in a modifier?
m

manueldidonna

02/12/2021, 11:19 PM
I'm not sure I understand the question but You need to be in a composable function to get the current value of an Ambient (now renamed to CompositionLocal)
z

Zach Klippenstein (he/him) [MOD]

02/12/2021, 11:19 PM
What do you mean by “used” and “in”? You can certainly read an ambient value then pass it to a modifier:
Copy code
val background = AmbientBackground.current
Box(Modifier.background(background))
You can also inline it:
Copy code
Box(Modifier.background(AmbientBackground.current))
If you are implementing your own custom modifier than needs to read ambients, probably the first thing to do is ask, does the modifier really need to read the ambient? Would it be more clear/less magic to just ask the caller to pass it in directly? If the answer to that is “no”, then you can use the
composed
helper to create a modifier that can read from the composition wherever it’s applied:
Copy code
fun Modifier.customBackground() = composed {
  this.background(AmbientBackground.current)
}
Note that that function is not composable itself. This is different and better than simply making a composable modifier factory function, since it guarantees that the composition will be read as close to the actual use site as possible, e.g. in case the caller calls your factory function very far away from wherever they end up passing the modifier to be used.
s

spierce7

02/12/2021, 11:46 PM
basically I’m trying to get key press events inside a composable. There seems to be a bug though on Android TV where DPAD events don’t make it into Jetpack Compose. https://issuetracker.google.com/issues/179925888 I can get the events inside
dispatchKeyEvent
via the Activity, but I need to somehow funnel them into compose. I was thinking it’d be fun to learn how to get them into the composable similar to the modifier that allows you to get key events in a composable.
l

Lukas K-G

03/05/2021, 3:31 PM
Hi @spierce7, did you find a way to get DPAD working in Jetpack Compose?
s

spierce7

03/05/2021, 3:59 PM
not natively
I had to override
dispatchKeyEvent
in the Activity, and I was able to get the events
jetpack compose was just eating all the events
l

Lukas K-G

03/05/2021, 4:00 PM
Thanks for the answer. 👍 Just saw that the bug you mentioned just got assigned. Maybe there is movement. 🙂