I have a requirement to perform an event after a c...
# compose
c
I have a requirement to perform an event after a composable has been showing for 3 seconds. This is my simple impl
Copy code
if (progress < 100) {
  CircularProgressIndicator()
    LaunchedEffect(Unit) {
        delay(3_000)
        doEvent()
    }
}
Are there cases where doEvent() would accidentally be called even if progress has reached 100? I know that in coroutines cancellation is cooperative, but not sure how all of this ties together.
s
Wouldn't imagine this ever not working as you want it to. Delay should cooperate with cancelation since it comes from inside
kotlinx.coroutines
. If you are super paranoid about this, slap in a
ensureActive()
in-between the two so that when delay ends, you check again if you are cancelled, and only if you are not you run the
doEvent()
.
"While a composable has been showing for 3 seconds" however may not be exactly the same as "this composable is in composition for 3 sceonds". If it's off-screen, does that matter for you? If the composable is on a screen which is right now in the middle of an animation where the screen is exiting, does that also matter to you? And other such questions may be important depending on what you are doing in the first place here.
c
In this example, it would never be "off screen" etc. It basically is always either the whole screen or not. Good point about animations, but I don't think we're too fussy about that. We just don't want to ever call
doEvent()
if progress == 100
👍 1
a
Btw this seems a good use case of
derivedStateOf
as reading
progress
directly will cause a lot of unnecessary recompositions.
👍 1