Consider this Compose snippet:
var count by remember { mutableStateOf(0) }
LaunchedEffect(count) {
println("Count is $count")
}What happens when count changes?
var count by remember { mutableStateOf(0) }
LaunchedEffect(count) {
println("Count is $count")
}LaunchedEffect runs its block when the key changes.
LaunchedEffect watches the key parameter. When count changes, it cancels the previous coroutine and launches a new one, printing the updated value.
Given this Compose code:
SideEffect {
println("SideEffect executed")
}When is this block executed?
SideEffect {
println("SideEffect executed")
}Think about when SideEffect is designed to run in the Compose lifecycle.
SideEffect runs after every recomposition, allowing side effects that need to happen after UI updates.
Look at this code:
var text by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
while(true) {
delay(1000)
println("Tick")
}
}
Button(onClick = { text += "a" }) {
Text(text)
}What is the problem with this LaunchedEffect?
var text by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
while(true) {
delay(1000)
println("Tick")
}
}
Button(onClick = { text += "a" }) {
Text(text)
}Consider what key Unit means for LaunchedEffect.
Using Unit as key means LaunchedEffect runs once when first composed and does not restart on recompositions, so it prints "Tick" every second as intended.
Which statement correctly describes the difference between LaunchedEffect and SideEffect in Jetpack Compose?
Think about coroutine support and timing of execution.
LaunchedEffect is designed to launch coroutines and supports suspend functions. SideEffect runs synchronously after every recomposition and cannot run suspend functions.
Analyze this code snippet:
LaunchedEffect {
println("Hello")
}What error will this cause?
LaunchedEffect {
println("Hello")
}LaunchedEffect(vararg keys: Any?, block: suspend CoroutineScope.() -> Unit); vararg keys can be omitted.
No syntax error: keys is vararg Any? and can be empty/omitted. The block runs once when the composable enters the composition, similar to LaunchedEffect(Unit).