rememberCoroutineScope

Jetpack Compose Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

This doesn't compile. What's the right fix?

@Composable
fun BackToTop(listState: LazyListState) {
    Button(onClick = { listState.animateScrollToItem(0) }) {
        Text("Top")
    }
}
Options
Hint 1 of 1

Is onClick a composable or a coroutine?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Get val scope = rememberCoroutineScope() and call scope.launch { listState.animateScrollToItem(0) }

Correct. Event handlers launch into a remembered scope.

Why not the others?
  • B Put a LaunchedEffect inside onClick. LaunchedEffect is a composable; onClick isn't a composable context.
  • C Use GlobalScope.launch. It compiles but outlives the screen and touches the list state after it's gone.
  • D Mark onClick suspend. The Button's onClick type is a plain () -> Unit.

30-second answer

Use rememberCoroutineScope() to launch coroutines from event handlers such as onClick, for example to scroll a list or open a drawer. LaunchedEffect runs because the composition changed; rememberCoroutineScope runs because the user did something. The scope is cancelled when the composable leaves composition.

Practise saying it · 30 s. No recording, just a timer

Explain rememberCoroutineScope vs LaunchedEffect.

Say your answer out loud, then check which of these points you covered:

  • rememberCoroutineScope for events
  • LaunchedEffect for composition changes
  • Cancelled when leaving composition
  • Business work goes to the ViewModel

Deep dive

You can't call suspend functions in onClick directly; launch them in the remembered scope.

For business logic like saving, call the ViewModel and let it use viewModelScope.

Scrolling and animations (animateScrollToItem, drawerState.open()) are the typical uses.

The scope uses the composition's main-thread context.

Common mistakes

  • Calling LaunchedEffect inside onClick (it's a composable and won't compile there).
  • Saving data in a rememberCoroutineScope so it's cancelled if the user leaves.
  • Creating a new CoroutineScope() in a composable.

Senior take & follow-ups

Event-driven vs composition-driven is the one-line distinction.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why not save data in this scope?

    Show hint

    It's cancelled when the composable leaves, which can cut the save short.

  2. How do you scroll to the top on tap?

    Show hint

    scope.launch { listState.animateScrollToItem(0) }.

Suggest a fix if something here is wrong or out of date.