Predict the output
userId changes from 1 to 2 while the first load is in progress. What happens?
@Composable
fun Profile(userId: String, onLoaded: (User) -> Unit) {
LaunchedEffect(userId) {
val user = fetchUser(userId)
onLoaded(user)
}
}Hint 1 of 1
What does a changed key do to the running coroutine?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A The load for 1 is cancelled and a load for 2 starts
Correct. A key change cancels the running effect and launches a new one.
Why not the others?
- B Both loads run and both call onLoaded. The first coroutine is cancelled, so it never reaches onLoaded.
- C Nothing happens until the first load finishes. Key changes restart the effect immediately.
- D The effect doesn't restart because keys only matter on first composition. Keys are compared on every recomposition.