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

Florian Walther (live streaming)

01/17/2022, 11:22 AM
How can I let a composable execute a one-off event? This composable contains and
AndroidView
which needs to call a method.
m

myanmarking

01/17/2022, 11:57 AM
LaunchedEffect(Unit) ?
f

Florian Walther (live streaming)

01/17/2022, 12:08 PM
For this i would have to pass the event Flow all the way down to the composable
is that correct?
m

myanmarking

01/17/2022, 12:11 PM
Since you are interested in the first composition, i don’t think it matters, unless you have some control variables like if(condition) composable()
place it as close as possible. i’m not sure the best practice here
z

Zoltan Demant

01/17/2022, 12:13 PM
If youre looking to call a method on the
AndroidView
itself, the factory call for it might be viable for that?
m

myanmarking

01/17/2022, 12:14 PM
Or maybe add the effect inside the composable, call a lambda, and do the action outside. Maybe the best practice i dont know 😛
f

Florian Walther (live streaming)

01/17/2022, 12:26 PM
@Zoltan Demant the problem is that I need it to happen one time, but compose usually works with state variables
I was considering passing an
updateThisThing = true
boolean and a callback to reset it
z

Zoltan Demant

01/17/2022, 12:35 PM
The factory function is only invoked once, but if your composable leaves & re-enters the composition it will get called again; is that the problem?
f

Florian Walther (live streaming)

01/17/2022, 12:36 PM
the viewmodel sends a one-off event (via a Flow) that the AndroidView nees to react to by calling a method
z

Zoltan Demant

01/17/2022, 12:41 PM
In that case I like what @myanmarking mentioned above, just using
LaunchedEffect(Unit)
to collect the flow & call the method. I think that makes for the best/cleanest code too, as compared to sending in a boolean & a callback to reset it!
f

Florian Walther (live streaming)

01/17/2022, 12:46 PM
But for this i would have to pass the event Flow all the way down to that composable
z

Zoltan Demant

01/17/2022, 12:51 PM
If you have a lot of nesting, it could be worth looking into using a
CompositionLocal
that contains the flow or some wrapper. How deep is this composable for you?
f

Florian Walther (live streaming)

01/17/2022, 12:53 PM
3 levels or so
i just noticed that I can't even call from the LaunchedEffect into the
AndroidView
So I guess my first idea of passing a boolean and a callback could be the way to go. But I am not sure
The other problem is that
update
can be called multiple times. This probably makes it not suitable for side-effects like this.
so I ended up passing the boolean & callback
seems to work
🥲 1
5 Views