Collecting flows safely in the UI

Learn to collect Kotlin flows safely in the Android UI with repeatOnLifecycle and collectAsStateWithLifecycle, so work stops in the background. About 20 minutes.

Why it matters

  • Collecting flows in a plain lifecycleScope.launch keeps the collection active while the app is in the background, wasting CPU, battery and network, and keeping location or sensor producers running.
  • A collector that keeps running after onStop can try a Fragment transaction after the state is saved, which throws an IllegalStateException.
  • Interviewers frequently test the relationship between the Android lifecycle and coroutine scopes, and why launchWhenStarted was deprecated.
  • repeatOnLifecycle and collectAsStateWithLifecycle are what make stateIn(..., WhileSubscribed(5_000), ...) in the ViewModel actually stop its upstream.

The simple explanation

  • A radio station broadcasting music constantly.
  • If you listen while walking (foreground), you enjoy the music.
  • If you put the radio in your pocket (background), the music still plays, wasting your battery.
  • repeatOnLifecycle is like a smart sensor that switches the radio off when you put it in your pocket and switches it on again when you take it out.

In Android, the UI lifecycle is volatile. An Activity or Fragment can move from STARTED to CREATED (its onStop runs, for example when the user presses Home) without being destroyed.

If you collect a flow inside a plain lifecycleScope.launch, the collection continues until the lifecycle is destroyed, including the whole time the app is in the background.

To solve this, we use repeatOnLifecycle. It is a suspend function that launches its block in a new coroutine every time the lifecycle reaches the given state (like STARTED) and cancels that coroutine when the lifecycle falls below it. It suspends the caller until the lifecycle is destroyed.

APIBehaviorUse Case
lifecycleScope.launchRuns until the lifecycle is destroyed.One-off work tied to the screen, such as starting a single action.
repeatOnLifecycle(STARTED)Launches the block at onStart, cancels it at onStop, repeats.Collecting flows in Activities and Fragments.
flowWithLifecycle(lifecycle, STARTED)The same idea as an operator on one flow.Collecting a single flow.
collectAsStateWithLifecycle()Collects into Compose State only while the lifecycle is at least STARTED.Jetpack Compose UI state.

With repeatOnLifecycle(Lifecycle.State.STARTED), collection is only active while the UI is visible. Because the collector unsubscribes, a ViewModel flow built with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ...) can stop its upstream 5 s later.

repeatOnLifecycle switches collection on and off
repeatOnLifecycle switches collection on and off Inside lifecycleScope.launch the screen calls repeatOnLifecycle(STARTED). At onStart it launches the block and the flow is collected. When the user presses Home, onStop cancels the collection. When the user returns, onStart launches the block again. When the lifecycle is destroyed, repeatOnLifecycle returns and the coroutine ends. Called inside lifecycleScope.launch Nothing runs in the background Returns, and the coroutine ends onStart LAUNCH, COLLECT onStop (HOME) CANCEL COLLECTION onStart (BACK) COLLECT AGAIN onDestroy Lifecycle Activity or Fragment repeatOnLifecycle (STARTED) Flow being collected
Collection runs only while the screen is at least STARTED: it is cancelled at onStop and launched again at the next onStart.

Notes

  • lifecycleScope.launch does not stop collecting when the app goes to the background.
  • repeatOnLifecycle is a suspend function, so it is called inside lifecycleScope.launch, usually in onCreate (Activity) or onViewCreated (Fragment).
  • It suspends until the lifecycle is DESTROYED. Code after it in the same coroutine runs only then.
  • repeatOnLifecycle(STARTED) cancels the block when the lifecycle drops below STARTED (at onStop) and launches it again at the next onStart.
  • In a Fragment, use viewLifecycleOwner.lifecycleScope and viewLifecycleOwner.repeatOnLifecycle. The Fragment's own lifecycle outlives its view.
  • To collect several flows, launch one child coroutine per flow inside the repeatOnLifecycle block. collect on a StateFlow never returns, so a second collect after it never runs.
  • In Jetpack Compose on Android, use collectAsStateWithLifecycle() (from lifecycle-runtime-compose) instead of collectAsState().
  • launchWhenStarted and the other launchWhenX functions are deprecated. They only suspend the coroutine below the state; the flow stays subscribed, so upstream work keeps running.
  • STARTED is the usual choice: the UI is visible. RESUMED stops collection whenever another activity partly covers the screen, which is rarely what you want.

Code example

A ViewModel exposes a ticking state with stateIn and WhileSubscribed(5_000). A Fragment collects it with repeatOnLifecycle, and a Compose screen collects it with collectAsStateWithLifecycle.

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
 
class TickerViewModel : ViewModel() {
    val uiState: StateFlow<String> = flow {
        var n = 0
        while (true) {
            emit("Tick $n")
            n++
            delay(1_000)
        }
    }
        .onCompletion { Log.d("Ticker", "upstream stopped") }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "Waiting")
}
 
class TickerFragment : Fragment() {
    private val viewModel: TickerViewModel by viewModels()
 
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View = TextView(requireContext())
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val label = view as TextView
        // WRONG: viewLifecycleOwner.lifecycleScope.launch { viewModel.uiState.collect { ... } }
        // keeps collecting in the background, so the upstream never stops.
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch { viewModel.uiState.collect { label.text = it } }
                // launch { viewModel.otherFlow.collect { ... } } // one launch per flow
            }
            // Anything here runs only after the view is destroyed.
        }
    }
}
 
@Composable
fun TickerScreen(viewModel: TickerViewModel = viewModel()) {
    val text by viewModel.uiState.collectAsStateWithLifecycle()
    Text(text)
}
  • Press Home: onStop cancels the collector, and about 5 s later Logcat shows "upstream stopped". Come back: the screen shows the last value, then the ticker restarts from 0, because the flow is cold and starts fresh.
  • With the WRONG version, the ticker keeps running in the background until the view is destroyed.
  • collectAsStateWithLifecycle() on a StateFlow uses its current value as the initial state, so the first frame never shows a placeholder.

Run the idea in plain Kotlin

A small model of repeatOnLifecycle(STARTED): a block that is launched at onStart and cancelled at onStop, collecting a cold flow that logs when it stops.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

// A tiny stand-in for Lifecycle: true means STARTED or above
val started = MutableStateFlow(false)

// Same idea as repeatOnLifecycle(STARTED): run the block while started, cancel it when not
suspend fun repeatWhileStarted(block: suspend CoroutineScope.() -> Unit) {
  started.collectLatest { isStarted ->
      if (isStarted) coroutineScope { block() }
  }
}

val ticks = flow {
  try {
      var n = 1
      while (true) {
          emit(n++)
          delay(200)
      }
  } finally {
      println("  producer stopped")
  }
}

fun main() = runBlocking {
  val screen = launch {
      repeatWhileStarted { ticks.collect { println("  tick " + it) } }
  }
  println("onStart")
  started.value = true
  delay(500)
  println("onStop")
  started.value = false
  delay(500)
  println("onStart")
  started.value = true
  delay(500)
  println("onDestroy")
  screen.cancel()
}

Expected output:

onStart
  tick 1
  tick 2
  tick 3
onStop
  producer stopped
onStart
  tick 1
  tick 2
  tick 3
onDestroy
  producer stopped
  • Nothing is printed between onStop and the second onStart: the collector and the producer are both gone. With the deprecated launchWhenStarted, the collector would only be suspended and the producer would not stop.

In production

Battery Drain via Background Flow Collection
  • Users reported high battery consumption while the app was in the background.
  • The app collected a location callbackFlow in lifecycleScope.launch in onCreate.
  • The collector stayed subscribed until onDestroy, so awaitClose never ran and location updates kept arriving while the user was not looking at the app.
The fix
  • Wrapped the collection in repeatOnLifecycle(Lifecycle.State.STARTED).
  • Now the collector is cancelled at onStop, awaitClose removes the location callback, and updates stop.
  • Verified with Logcat and the Android Studio Energy Profiler that location requests stop when the app goes to the background.
IllegalStateException during Fragment Transaction
  • App crashed with IllegalStateException: Can not perform this action after onSaveInstanceState.
  • A flow collected in lifecycleScope.launch emitted a result while the app was in the background.
  • The collect block called commit() on a Fragment transaction, after the Fragment's state had already been saved.
The fix
  • Switched the collection to viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED).
  • The collector is now cancelled at onStop, which runs before the state is saved, so it can no longer commit a transaction in that window.
  • Moved the navigation result into UI state, so it is handled when the screen is started again instead of being lost.

Common mistakes

  • Using lifecycleScope.launch for UI state. The collection continues in the background, wasting resources and keeping WhileSubscribed upstreams alive. Use repeatOnLifecycle(STARTED).
  • Using launchWhenStarted. It is deprecated and only suspends the coroutine; the flow stays subscribed and its producer keeps running. Use repeatOnLifecycle.
  • Collecting two flows one after the other in the same block. collect on a StateFlow never returns, so the second collect never starts. launch each collection separately inside repeatOnLifecycle.
  • Putting code after repeatOnLifecycle in the same coroutine. repeatOnLifecycle suspends until the lifecycle is destroyed, so that code runs only at the end. Put it before the call or in another coroutine.
  • Using the Fragment's lifecycle instead of viewLifecycleOwner. The Fragment can outlive its view (for example on the back stack), so the collector keeps updating a destroyed view. Use viewLifecycleOwner.
  • Using collectAsState in Compose on Android. It keeps collecting while the app is in the background. Use collectAsStateWithLifecycle.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you collect a Flow in an Android Activity safely?”

“What is the difference between lifecycleScope.launch and repeatOnLifecycle?”

“Why is it a bad idea to collect flows while the app is in the background?”

“How would you handle flow collection in Jetpack Compose?”

Quiz

Which API is recommended for collecting flows in a Fragment so that collection stops when the app is in the background?

What happens to the coroutine started by repeatOnLifecycle(STARTED) when the user presses the Home button?

In Jetpack Compose on Android, which function is recommended for collecting a ViewModel's StateFlow?

A Fragment does this inside viewLifecycleOwner.lifecycleScope.launch: repeatOnLifecycle(STARTED) { uiState.collect { render(it) }; events.collect { handle(it) } }. uiState is a StateFlow. What goes wrong?

0 of 4 answered

Mini task

Task: Implement a Lifecycle-Aware UI Observer

  1. Create a ViewModel that exposes a StateFlow<Int> built from a flow { } that emits an increasing number every second, converted with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0).
  2. Add onEach { Log.d("Counter", "produced $it") } before stateIn, so you can see when the producer runs.
  3. In a Fragment, in onViewCreated, collect the flow with viewLifecycleOwner.lifecycleScope.launch and viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED), and log each value the UI receives.
  4. Run the app and press Home. Check in Logcat that "received" lines stop at once and "produced" lines stop about 5 s later. Return to the app and see both resume.
  5. Replace repeatOnLifecycle with a plain collect inside lifecycleScope.launch and repeat the test.

Done Condition: With repeatOnLifecycle, both the collector and the producer stop in the background. With the plain launch, both keep logging until you leave the screen.

Next: ViewModel and UI state