Search code examples
androidkotlinandroid-jetpack-compose

How to make LaunchedEffect run once and never again?


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.


Solution

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