LaunchedEffect
changes in value
is the implementation of println
But why it is also executed when entering the default value
for the first time, it is really confusing, why is it designed like this.
LaunchedEffect(value) {
println("--1--")
}
How to avoid first execution?
CodePudding user response:
LaunchedEffect starts when the Composable enters the composition and restarts when the key(s) is changed. You can't avoid executing it, but inside you can check if it's the default value, meaning this is the first run.
LaunchedEffect(value) {
if (value != defaultValue) println("--1--")
}
CodePudding user response:
How to avoid first execution
If you want to avoid only first execution, you wrap your LaunchedEffect(Unit)
in an if{}
block - if this is what you want.
if(yourCondition){
LaunchedEffect(){
}
}
LaunchedEffect
triggers
- during initial composition or if it's key changes
- during initial composition, which also included adding it in view-tree conditionally, even in case of re-composition.
For eg -> If you first if condition during composition added the LaunchedEffect
in the view-tree, and if removed in further re-composition and added again (it will again be re-launched).