Android & Jetpack Compose (50 Qs)•Part 1: Architecture, Jetpack Compose & Core Components (1 - 10)
What are Side-Effects in Jetpack Compose: `LaunchedEffect` vs `rememberCoroutineScope` vs `DisposableEffect`?
senior LevelCode ExampleComponentsDocker & ContainersSystem Design
In Simple Words: A Composable function should be pure and free of side-effects. Side-Effect handlers safely execute asynchronous tasks:
LaunchedEffect(key): Launches a coroutine when the composable enters the composition. Ifkeychanges, the ongoing coroutine is cancelled and relaunched.rememberCoroutineScope(): Creates a coroutine scope bounded to the composable's lifecycle, used to launch coroutines in response to user event callbacks (e.g. button clicks).DisposableEffect(key): Used for side-effects that require cleanup (e.g. registering/unregistering system broadcast receivers or location listeners). InvokesonDispose { ... }when leaving the composition.
kotlin
@Composable
fun UserScreen(userId: String, viewModel: UserViewModel) {
// Runs when userId changes:
LaunchedEffect(userId) {
viewModel.loadUser(userId)
}
val coroutineScope = rememberCoroutineScope()
Button(onClick = {
coroutineScope.launch { viewModel.refresh() }
}) { Text("Refresh") }
}