What distinguishes LaunchedEffect from rememberCoroutineScope in the context of coroutine management in Jetpack Compose?
sobes.tech AI
Answer from AI
LaunchedEffect and rememberCoroutineScope are two different ways to manage coroutines in Jetpack Compose, differing in lifecycle and launch context.
-
LaunchedEffect launches a coroutine tied to the lifecycle of a specific effect in Compose. It automatically cancels when the effect's keys change or when the Composable leaves the composition. It is convenient for one-time or state-dependent tasks.
-
rememberCoroutineScope returns a
CoroutineScopeassociated with the Composable's lifecycle, which can be used to launch coroutines manually, e.g., in event handlers. Coroutines launched in this scope are canceled when the Composable is destroyed.
Example:
@Composable
fun Example() {
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
// Async operation on click
}
}) {
Text("Click me")
}
LaunchedEffect(Unit) {
// Runs once when entering composition
// e.g., load data
}
}
In summary, LaunchedEffect is suitable for reactive and one-time effects, while rememberCoroutineScope is for launching coroutines on events within a Composable.