is there any variation of LaunchedEffect(boolean) ...
# compose
m
is there any variation of LaunchedEffect(boolean) that will only run when it is true?. Using a boolean works, but then the scope is restarted in true -> false. I have nothing to do on false so it seems quite a waste
a
Copy code
if (condition) {
  LaunchedEffect...
m
Doing like that, the effect is disposed when it is false ?
a
Yes, the effect leaves the composition when the condition branch is not taken in a recomposition
m
oh, that makes things simpler. Thanks!
👍🏽 1
👍 1
a
Just like when you do
Copy code
if (condition) {
  Text("condition is true!")
}
m
yeah, it makes sense
Doing something like this, is it safe:
Copy code
LaunchedEffect(key1 = Unit) {
    while (true) {
        delay(autoScrollInterval)
        state.animateToNextPage()
    }
}
i’m concerned about while(true), maybe i should replace with isActive instead 😛 ?
delay is cancellable, but it should be the best practice in this case i think
code is something like this:
Copy code
if (autoScroll.value) {
    LaunchedEffect(key1 = Unit) {
        while (isActive) {
            delay(autoScrollInterval)
            state.animateToNextPage()
        }
    }
}
z
It probably doesn't matter. But what you should also do is pass dependencies to your effect as keys - in this case
state
. This is more correct because if the value of
state
changes between compositions, it doesn't make sense for the effect to continue executing on the old state. For
autoScrollInterval
, if the interval changes while scrolling, you probably don't want to cancel the current scroll, but rather just use the new interval for the next iteration, so it's better to use
rememberUpdatedState
and not pass it as a key.
m
oh nice. thank you