Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 104 ยท Coroutines and Background Work

Collecting Flows Safely

Collect Kotlin Flows without wasting work or leaking: repeatOnLifecycle, flowWithLifecycle, callbackFlow, debounce for search and flatMapLatest explained.

A Flow is a stream of values over time: location updates, database changes, text typed into a search box. Producing those values often costs something, such as GPS battery, a database observer or a network socket. On Android, the screen that consumes the stream is not always visible. If the user presses Home and your app keeps collecting, the work continues for nobody. If you collect in the wrong place, you can also receive the same stream twice, or crash when you touch a view that no longer exists.

This lesson covers the two halves of the problem. First, where to collect so that collection starts when the screen is visible and stops when it is not: repeatOnLifecycle, flowWithLifecycle and Compose's collectAsStateWithLifecycle. Second, how to shape a stream so it behaves well, using the operators behind a search-as-you-type box: debounce, distinctUntilChanged and flatMapLatest, plus callbackFlow for turning old callback APIs into flows. The Flow basics are in Kotlin Flows, and StateFlow was used in the earlier architecture lessons. The Android classes are real only on a device, so the Android snippets are read-only and the TryIts are runnable stand-ins built on the real coroutines library.

Why lifecycleScope.launch { flow.collect {} } is a trap

Beginners often write this in an activity or fragment:

Kotlin
// read-only example: a common bug
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launch {
        viewModel.uiState.collect { render(it) }   // keeps running when the app is in the background
    }
}

lifecycleScope is cancelled only in onDestroy. Between onStop and onDestroy, which can last hours, the collector is still alive. A StateFlow that is shared with WhileSubscribed stays active because it has a subscriber. A callback-based flow keeps its sensor or listener registered. The UI is updated while invisible, which wastes battery and, with views, can touch a destroyed hierarchy.

The fix is to collect only while the lifecycle is at least STARTED.

repeatOnLifecycle

repeatOnLifecycle(Lifecycle.State.STARTED) is a suspending function that runs its block every time the lifecycle reaches STARTED and cancels it when the lifecycle drops below STARTED (at onStop). When the user returns, the block is launched again from scratch, so each stint collects fresh.

Kotlin
// read-only example
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiState.collect { render(it) }
        }
    }
}

Two details matter:

  • Launch multiple collectors inside the block, each in its own launch. A collect never returns for an endless flow, so a second collect placed after it would never run.
  • The outer lifecycleScope.launch is still cancelled in onDestroy; repeatOnLifecycle just adds the pause between onStop and the next onStart.
Kotlin
// read-only example: two collectors in one block
repeatOnLifecycle(Lifecycle.State.STARTED) {
    launch { viewModel.uiState.collect { render(it) } }
    launch { viewModel.events.collect { showMessage(it) } }
}
stateDiagram-v2
    [*] --> Idle: onCreate
    Idle --> Collecting: onStart
    Collecting --> Idle: onStop (block cancelled)
    Idle --> Collecting: onStart (block restarted)
    Idle --> [*]: onDestroy

The block runs only in the Collecting state. Every return to STARTED restarts it.

flowWithLifecycle and collectAsStateWithLifecycle

For a single flow, flowWithLifecycle is a shorter spelling. It returns a flow that stops upstream work when the lifecycle is below the given state:

Kotlin
// read-only example
lifecycleScope.launch {
    viewModel.uiState
        .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
        .collect { render(it) }
}

In Compose, you rarely write either. collectAsStateWithLifecycle() turns a StateFlow into Compose State and starts or stops collection with the lifecycle of the screen:

Kotlin
// read-only example
@Composable
fun NotesScreen(viewModel: NotesViewModel = viewModel()) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    NotesContent(state)
}

Prefer it over the plain collectAsState(), which keeps collecting while the app is in the background. StateFlow and collectAsStateWithLifecycle covers the Compose side in depth.

The first stand-in builds a tiny lifecycle with a state flow and a collectWhileStarted helper that does the same thing as repeatOnLifecycle(STARTED). It also uses callbackFlow, the real coroutines function, to wrap a fake sensor with a classic register/unregister callback API. Watch the "listeners active" count in a naive collector and in the safe one.

Kotlin repeatOnLifecycle stand-in with a callbackFlow sensor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the naive run, the listener stays registered while the screen is stopped, and render 3 happens for a screen nobody can see. In the safe run, the listener is removed at the stop and registered again at the next start, so value 3 is simply never delivered to a UI that is not there. (If you must not lose values, expose them through a state holder such as StateFlow in the ViewModel, which keeps the latest value for the next collector.)

callbackFlow in real code

Many Android APIs predate coroutines: location updates, connectivity callbacks, sensor listeners. callbackFlow is the bridge. The pattern always has three parts: register a callback that calls trySend, then awaitClose { unregister } to clean up when the collector stops, which happens automatically when repeatOnLifecycle cancels collection. Forgetting awaitClose is a compile error, which is deliberate: it prevents leaked listeners.

Kotlin
// read-only example: connectivity as a flow
fun ConnectivityManager.networkAvailable(): Flow<Boolean> = callbackFlow {
    val callback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) { trySend(true) }
        override fun onLost(network: Network) { trySend(false) }
    }
    registerDefaultNetworkCallback(callback)
    awaitClose { unregisterNetworkCallback(callback) }
}.distinctUntilChanged()

A search box is a perfect stream: every keystroke is an event. Sending a request for each letter would waste data and make results flicker. Three operators fix it.

  • debounce(300) waits until the user pauses typing for 300 ms, and drops everything typed in between.
  • distinctUntilChanged() ignores a query that equals the previous one, for example when the user adds and deletes a space.
  • flatMapLatest { query -> search(query) } starts a new search for each query and cancels the previous one if it is still running. Without it, a slow response for an old query can arrive after a fast response for the new one and overwrite it with stale results.

A typical ViewModel connects them to a StateFlow and shares the result with stateIn:

Kotlin
// read-only example
class SearchViewModel(private val repo: LessonRepository) : ViewModel() {

    private val query = MutableStateFlow("")

    val results: StateFlow<List<Lesson>> = query
        .map { it.trim() }
        .debounce(300)
        .distinctUntilChanged()
        .flatMapLatest { text ->
            if (text.length < 2) flowOf(emptyList()) else repo.search(text)
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun onQueryChange(text: String) { query.value = text }
}

The WhileSubscribed(5_000) part keeps the upstream alive for five seconds after the last collector leaves, so a rotation (which stops and restarts collection within moments) does not restart the search.

Use debounce for search boxes, but not for buttons. A debounced tap handler delays the user's own action, which feels broken. For taps, disable the button while a request is running, or ignore repeats.

The second stand-in runs the real operators on a scripted typing session: the user types "kot", pauses, types "kotlin" quickly, adds a trailing space, then edits to "ko". The fake search takes a long time for "kot" and a short time for the others, so you can watch the stale request being cancelled.

Kotlin Search-as-you-type: debounce, distinctUntilChanged, flatMapLatest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output in order. All eight keystrokes are printed, but only a few searches start. "kot" begins after the first pause, and while it is still running the "kotlin" query arrives, so the "kot" request is cancelled and only the newest answer reaches the UI. The trailing space produces the same trimmed text and is dropped by distinctUntilChanged, and the empty text is filtered out so no request is sent for it.

Common mistakes

  • Collecting in lifecycleScope.launch without repeatOnLifecycle. The collector lives until onDestroy.
  • Two collect calls in a row in the same coroutine. The second never runs. Use two launch blocks.
  • Using collectAsState() instead of collectAsStateWithLifecycle() on Android, keeping work alive in the background.
  • Forgetting awaitClose cleanup in a callbackFlow, which leaks the listener.
  • Using flatMapMerge or map { search() } for search, letting old responses overwrite new ones. flatMapLatest is the right choice.
  • Debouncing in the UI instead of the ViewModel. The ViewModel survives rotation, so the pipeline and its pending query survive too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does repeatOnLifecycle(Lifecycle.State.STARTED) do with its block?

    The block is launched on every return to STARTED and cancelled at STOPPED, so flow collection and its upstream work stop while the screen is not visible.
  2. 2. In a callbackFlow, what is awaitClose for?

    awaitClose suspends until the collector cancels or the channel closes, and its block is where you unregister callbacks so nothing leaks.
  3. 3. Why use flatMapLatest for a search box?

    flatMapLatest cancels the inner flow of the previous value. Only the most recent query can deliver results.
  4. 4. Which line is a bug in an activity?

    That collector keeps running between onStop and onDestroy. The others all pause collection when the screen is not visible.
  5. 5. What does distinctUntilChanged add to a debounced search query?

    It compares each value with the previous one and skips repeats, so the same text never triggers a second request.

Summary

  • Do not collect flows in a bare lifecycleScope.launch: the collector outlives the visible screen.
  • Use repeatOnLifecycle(STARTED) (or flowWithLifecycle) in Views code and collectAsStateWithLifecycle() in Compose.
  • Put separate collectors in separate launch blocks inside the lifecycle block.
  • callbackFlow wraps callback APIs: register, trySend, and clean up in awaitClose.
  • For search: debounce waits for a pause, distinctUntilChanged drops repeats and flatMapLatest cancels outdated requests.
  • Share the pipeline with stateIn(viewModelScope, WhileSubscribed(5_000), initial) so rotation does not restart it.
  • The Android lifecycle code is read-only; the TryIts run the real operators with a fake lifecycle, sensor and search.

Next: WorkManager