Collecting flows safely in the UI
Why it matters
- Collecting flows in a plain
lifecycleScope.launchkeeps 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
onStopcan try a Fragment transaction after the state is saved, which throws anIllegalStateException. - Interviewers frequently test the relationship between the Android lifecycle and coroutine scopes, and why
launchWhenStartedwas deprecated. repeatOnLifecycleandcollectAsStateWithLifecycleare what makestateIn(..., 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.
repeatOnLifecycleis 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.
| API | Behavior | Use Case |
|---|---|---|
lifecycleScope.launch | Runs 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.
Notes
lifecycleScope.launchdoes not stop collecting when the app goes to the background.repeatOnLifecycleis a suspend function, so it is called insidelifecycleScope.launch, usually inonCreate(Activity) oronViewCreated(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 belowSTARTED(atonStop) and launches it again at the nextonStart.- In a Fragment, use
viewLifecycleOwner.lifecycleScopeandviewLifecycleOwner.repeatOnLifecycle. The Fragment's own lifecycle outlives its view. - To collect several flows,
launchone child coroutine per flow inside therepeatOnLifecycleblock.collecton a StateFlow never returns, so a secondcollectafter it never runs. - In Jetpack Compose on Android, use
collectAsStateWithLifecycle()(fromlifecycle-runtime-compose) instead ofcollectAsState(). launchWhenStartedand the otherlaunchWhenXfunctions are deprecated. They only suspend the coroutine below the state; the flow stays subscribed, so upstream work keeps running.STARTEDis the usual choice: the UI is visible.RESUMEDstops 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:
onStopcancels 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 aStateFlowuses its currentvalueas 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
- Users reported high battery consumption while the app was in the background.
- The app collected a location
callbackFlowinlifecycleScope.launchinonCreate. - The collector stayed subscribed until
onDestroy, soawaitClosenever ran and location updates kept arriving while the user was not looking at the app.
- Wrapped the collection in
repeatOnLifecycle(Lifecycle.State.STARTED). - Now the collector is cancelled at
onStop,awaitCloseremoves 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.
- App crashed with
IllegalStateException: Can not perform this action after onSaveInstanceState. - A flow collected in
lifecycleScope.launchemitted a result while the app was in the background. - The
collectblock calledcommit()on a Fragment transaction, after the Fragment's state had already been saved.
- 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
WhileSubscribedupstreams alive. UserepeatOnLifecycle(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.
collecton a StateFlow never returns, so the secondcollectnever starts.launcheach collection separately insiderepeatOnLifecycle. - Putting code after repeatOnLifecycle in the same coroutine.
repeatOnLifecyclesuspends 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
- Create a
ViewModelthat exposes aStateFlow<Int>built from aflow { }that emits an increasing number every second, converted withstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0). - Add
onEach { Log.d("Counter", "produced $it") }beforestateIn, so you can see when the producer runs. - In a Fragment, in
onViewCreated, collect the flow withviewLifecycleOwner.lifecycleScope.launchandviewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED), and log each value the UI receives. - 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.
- Replace
repeatOnLifecyclewith a plaincollectinsidelifecycleScope.launchand 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.