Home > Net >  How to make LaunchedEffect run once and never again?
How to make LaunchedEffect run once and never again?

Time:01-25

I know that LaunchedEffect(key) is executed when composition starts, and is also cancelled and re-executed again when the key changes. However, I want it to be executed only once and never again, I am using the following workaround but I feel like I am missing something:

if (!launchedBefore) {
   LaunchedEffect(null) {
      //stuff

      launchedBefore = true
   }
}

The code above works just fine. But it feels like a stretched workaround while something much simpler can be done. Am I misunderstanding how LaunchedEffect fully works?

I tried using null and Unit as keys cuz they never changed, but the code is executed every time a composition takes place.

CodePudding user response:

LaunchedEffect(Unit) should execute only once when the composition starts. The only time it would get re-executed during recomposition is if it gets removed from the view tree during one of the previous recompositions. An example would be if you have it within a condition whose value changes at some point (in an if block, when block or any other conditional statement).

I would assume that the problem with recomposing lies in the other part of the code that is not shown in your snippet. Check if the LaunchedEffect is nested in a conditional block that might cause it to get executed after a recomposition.

CodePudding user response:

fun LaunchedEffect(key1: Any?, key2: Any?, block: suspend CoroutineScope.() -> Unit): Unit

You should use a key that re-launch the composition every time It changes. E.g

  var counter: Int = 0
  LaunchedEffect(counter) {
    Button (
      onClick = { counter   }
    )
  }

In this example the LaunchedEffect should re-launch the composition every time you click the button. For more info click her

  • Related