Compose Chronicles: Exploring The rememberCoroutineScope Superpower 💪

Jesseosile
2 min readMar 27, 2024

--

Welcome back! Today we’re continuing our discussion on Side Effects in Jetpack Compose. We last talked about LaunchedEffect. You can check out that article here.

Today we’ll be exploring the rememberCoroutineScope effect handler. Let’s define a few terminologies.

WHAT ARE COROUTINES?

Coroutines are lightweight processes (requiring less memory and computing power) that allow you to perform multiple tasks concurrently without halting or blocking the main program. This asynchronous execution means tasks can run independently without waiting for each other to finish.

WHAT IS A COROUTINE SCOPE?

A coroutine scope is like a manager for your coroutines. It creates them, lets them share data or resources, and can even cancel them all at once.

WHAT IS rememberCoroutineScope?

This composable function returns a coroutine scope that is canceled automatically when the composable is removed from the composition tree. This ensures coroutines launched within the scope don’t continue to run unnecessarily and potentially leak resources.

Another reason for rememberCoroutineScope is to allow launching coroutines outside of a composable.

For example, imagine a button in your composable. When clicked, you want to introduce a 2-second delay before invoking a lambda that updates some UI state. In this scenario, rememberCoroutineScope comes into play because you can't directly launch coroutines within a button click handler (which is not a composable).

If we tried calling delay directly the onClick lambda we would get an error because the onClick lambda is not a suspend function. Thanks to rememberCoroutineScope, this is possible.

Thank you for reading and see you on the next one. 😁👋

--

--