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

mbonnin

02/23/2020, 2:35 PM
Is it possible/recommended to use Ambients from a click listener ? I get
Composition requires an active composition context
when trying to do that.
https://kotlinlang.slack.com/archives/CJLTWPH7S/p1577141808038500 : looks like it expected. Trying to retrieve a reference to the ambient and then capturing it in
onClick
crashes the compiler though...
a

Adam Powell

02/23/2020, 2:39 PM
No, you have to capture the ambient value outside the click listener body. You can then use the captured value inside. e.g.
Copy code
val foo = myAmbient.current
SomeComposable(..., onClick = { foo.doThing() })
☝️ 1
m

mbonnin

02/23/2020, 2:40 PM
Thanks for the answer. I tried capturing the ambient but it crashes the compiler at the moment
a

Adam Powell

02/23/2020, 2:41 PM
It'll have a better error message later
l

Leland Richardson [G]

02/23/2020, 4:45 PM
what is the code you’re trying to write? In most cases it should just highlight the call with red squiggles and say that you cannot call composable functions outside of composable functions.
m

mbonnin

02/23/2020, 4:47 PM
It was something like
Copy code
onClick =  {
        val sessionId = ActiveSessionIdAmbient.current
        // trigger an API call with sessionId
    }
a

Adam Powell

02/23/2020, 4:48 PM
@Leland Richardson [G] might be that the compose ide plugin is too old in the studio canaries?
l

Leland Richardson [G]

02/23/2020, 4:49 PM
could be. although the logic in the compiler that handles right now is indeed buggy so i also expect there to be a number of situations currently where it is not reported correctly
m

mbonnin

02/23/2020, 4:51 PM
I'm on AGP
4.0.0-alpha09
and I can confirm it's not highlighted
2 Views