Skip to main content
InterviewHubPRO
Section Overview
Q10

Question 10 of 50

Part 1: Architecture, Jetpack Compose & Core Components (1 - 10)

20%
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:

  1. LaunchedEffect(key): Launches a coroutine when the composable enters the composition. If key changes, the ongoing coroutine is cancelled and relaunched.
  2. 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).
  3. DisposableEffect(key): Used for side-effects that require cleanup (e.g. registering/unregistering system broadcast receivers or location listeners). Invokes onDispose { ... } 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") }
}