Is it possible/recommended to use Ambients from a ...
# compose
m
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
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
Thanks for the answer. I tried capturing the ambient but it crashes the compiler at the moment
a
It'll have a better error message later
l
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
It was something like
Copy code
onClick =  {
        val sessionId = ActiveSessionIdAmbient.current
        // trigger an API call with sessionId
    }
a
@Leland Richardson [G] might be that the compose ide plugin is too old in the studio canaries?
l
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
I'm on AGP
4.0.0-alpha09
and I can confirm it's not highlighted