Home > database >  What is difference between LaunchedEffect parameters?
What is difference between LaunchedEffect parameters?

Time:10-11

When I use LaunchedEffect in jetpack compose screen, what is difference between using viewmodel and Unit in key1 parameter?

CodePudding user response:

From the documentation (https://developer.android.com/jetpack/compose/side-effects#launchedeffect) :

LaunchedEffect restarts when one of the key parameters changes.

Using Unit would guarantee this will only run once for the composable scope (Unit being an object) no matter how many times it is recomposed, where as if the viewmodel "changes" (equals method returns false) it would be "launched" again (lambda block would execute again, cancelling the previous suspend block first).

CodePudding user response:

LaunchedEffect is remember with CoroutineScope under the hood. suspend block gets invoked when it enters composition and any time as remember its only key or one of it's keys change

@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
    key1: Any?,
    block: suspend CoroutineScope.() -> Unit
) {
    val applyContext = currentComposer.applyCoroutineContext
    remember(key1) { LaunchedEffectImpl(applyContext, block) }
}
  • Related