RitchyCZE
RitchyCZE

Reputation: 178

What is difference between LaunchedEffect parameters?

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

Upvotes: 1

Views: 529

Answers (2)

Thracian
Thracian

Reputation: 67293

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

Upvotes: 0

Mark
Mark

Reputation: 9929

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

Upvotes: 2

Related Questions