skip to content

In Jetpack Compose, why do you use rememberCoroutineScope rather than LaunchedEffect to show a snackbar from a button's onClick?

level: juniorimportance: must knowfreq 70%

answer

  1. onClick is not composable
  2. showSnackbar suspends
  3. a scope bound to the call site
  4. cancelled when the call leaves

basics

~20 s

LaunchedEffect is a composable, so it cannot be called from onClick, and showSnackbar is a suspend function that needs a coroutine. rememberCoroutineScope returns a scope bound to that point of the composition: launch from the click, cancelled when the composable leaves.

solid answer

~50 s

Effects such as `LaunchedEffect` run work in response to composition; a click is an event that happens later, inside a non-composable lambda, so `LaunchedEffect` cannot be called there. `SnackbarHostState.showSnackbar` suspends until the snackbar is dismissed, so it needs a coroutine. `val scope = rememberCoroutineScope()` returns the same `CoroutineScope` across recompositions, dispatching on the composition's apply dispatcher (the UI thread on Android) unless you pass a context, and cancels it when the call leaves composition. In `onClick` you write `scope.launch { snackbarHostState.showSnackbar("Saved") }`. The runtime docs say not to fake this with a `LaunchedEffect` keyed on a `MutableState` you set from the click, and not to launch into any scope from the composable body itself. A failure that already lives in state, such as a failed download shown on arrival, is the opposite case: that is `LaunchedEffect` keyed on the failure.

go deeper

for a junior

Recall that onClick cannot call composables, so you get a scope with rememberCoroutineScope and launch the suspend call from it.

for a middle

Explain the scope's guarantees: one instance per call site, cancelled on leaving composition, UI dispatcher by default.

for a senior

Separate composition-triggered work from event-triggered work in a code review, and move work that must outlive the screen to a longer-lived owner.

for a principal

Agree a team convention for events versus state so snackbars and navigation are not driven by flags that replay on recreation.

## Two kinds of trigger Compose distinguishes work started **by composition** from work started **by an event**. - **By composition:** "while this screen shows download 42, watch its progress". The trigger is that some UI is composed with some input. That is `LaunchedEffect(downloadId)`. - **By an event:** "when the user taps Retry, show a snackbar". The trigger is a callback that fires after composition is done. That needs a coroutine scope you can launch into from the callback. `LaunchedEffect` is a `@Composable` function, and `onClick` is an ordinary lambda, so calling it there is a compile error. Even if it were allowed, an effect describes a lifetime in the tree, not a reaction to a tap. ## What rememberCoroutineScope returns `rememberCoroutineScope()` is an inline composable that remembers a `CoroutineScope` at its call site: - **Same instance** across recompositions, so capturing it in `onClick` is safe. - **Bound to the composition:** its job is a child of the composition's job, and the scope is **cancelled when the call leaves composition** (the screen is popped, a branch turns false, the composition is disposed). - **Dispatcher:** unless you supply one, coroutines run on the composition's apply dispatcher, which on Android is the window's UI thread, so suspending UI calls like `showSnackbar` or `animateScrollToItem` work directly. - **Lazy:** the runtime creates the scope's coroutine context only when it is first used, so a scope that is never launched into costs almost nothing. ```kotlin @Composable fun RetryBar(snackbarHostState: SnackbarHostState, onRetry: () -> Unit) { val scope = rememberCoroutineScope() Button(onClick = { onRetry() scope.launch { snackbarHostState.showSnackbar("Retrying download") } }) { Text("Retry") } } ``` ## Choosing between the two | Situation | Use | Why | |---|---|---| | A tap, a swipe, a menu choice | `rememberCoroutineScope` + `launch` in the callback | The event happens outside composition | | A failed download already present in the screen's state | `LaunchedEffect(failureId)` | Composition with that input is the trigger | | A coroutine you must cancel by hand (stop an animation on a second tap) | `rememberCoroutineScope`, keep the `Job` | You control the job's lifetime manually | ## Mistakes interviewers look for 1. **Launching from the composable body.** `scope.launch { ... }` written directly in the body runs on every recomposition and may run for a composition that is discarded. The runtime docs say jobs should never be launched into any scope as a side effect of composition itself. 2. **Turning a click into state to trigger an effect.** Setting `var showMessage by mutableStateOf(true)` in `onClick` and keying `LaunchedEffect(showMessage)` on it works by accident: it misses a second tap with the same value and runs again whenever the screen re-enters composition. The `LaunchedEffect` documentation names this pattern and points to `rememberCoroutineScope` instead. 3. **Using a scope that outlives the screen** for UI work. A global or Activity-wide scope keeps showing a snackbar or scrolling a list after the screen is gone; lifecycle scopes are a separate subject outside this lesson. 4. **Passing a Job in the context.** `rememberCoroutineScope { SupervisorJob() }` is rejected: the runtime does not throw, but returns a scope whose job has already failed, so nothing launches. ## The state-driven case, for contrast When the download fails, the failure arrives as state the screen already renders. Nothing was tapped, so there is no callback to launch from; composition with that failure is the trigger: ```kotlin failure?.let { f -> LaunchedEffect(f.id) { snackbarHostState.showSnackbar("Download failed: ${f.reason}") onFailureShown(f.id) } } ``` Keying on the failure's id shows each failure once, and reporting it as shown stops it from appearing again when the screen re-enters composition. ## Summary for the interview - Composition-triggered work is an effect; event-triggered work is a launch from a remembered scope. - The scope is one instance per call site and dies with it. - Never launch from the composable body, and never feed a click through state into an effect. ## Work that must outlive the screen If the work must finish even when the user leaves (saving a file, uploading), a composition-bound scope is the wrong owner, because leaving cancels it. Hand the work to a longer-lived owner and let the screen only observe the result.

  • In Jetpack Compose, what happens if you pass a context containing a Job to rememberCoroutineScope?
    The scope's job must be a child of the composition, so a parent `Job` is not allowed. The function does not throw, because composable functions do not fully support exceptions; instead it returns a scope whose job has already completed exceptionally with an `IllegalArgumentException`, and launching into it does nothing.
  • In Jetpack Compose, which dispatcher runs a coroutine launched from rememberCoroutineScope by default?
    The composition's apply dispatcher, taken from the `Recomposer`; on Android that is the window's UI-thread dispatcher. You can add another dispatcher through the optional `getContext` lambda, which is called once, but heavy work usually belongs to code outside the composable that switches dispatchers itself.

  • You can call LaunchedEffect from onClick if you give it a key
  • A coroutine from rememberCoroutineScope keeps running after the screen is popped
  • Launching into the scope from the composable body is fine
  • rememberCoroutineScope returns a new scope on every recomposition
  • Set a boolean in onClick and key a LaunchedEffect on it to show a snackbar