gaohomway
gaohomway

Reputation: 4060

Jetpack Compose LaunchedEffect confusing

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?

Upvotes: 2

Views: 4556

Answers (3)

Denis Perfomer
Denis Perfomer

Reputation: 187

You can just make your custom effect like this UpdateEffect:

/**
 * The same as [LaunchedEffect] but skips the first invocation
 */
@Composable
fun UpdateEffect(key: Any, block: suspend CoroutineScope.() -> Unit) {
    var isTriggered by remember { mutableStateOf(false) }

    LaunchedEffect(key) {
        if (isTriggered) {
            block()
        } else {
            isTriggered = true
        }
    }
}

And then replace your LaunchedEffect with UpdateEffect.

Upvotes: 9

Ritt
Ritt

Reputation: 3339

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).

Upvotes: 0

bylazy
bylazy

Reputation: 1295

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--")
}

Upvotes: 1

Related Questions