skip to content

A ferry-departures Activity on Jetpack Lifecycle calls lifecycleScope.launch { departures.collect { } } in onStart; why does it keep polling in the background and show duplicate updates, and what fixes it?

level: seniorimportance: should knowfreq 55%

answer

  1. when is lifecycleScope cancelled
  2. one new collector per onStart
  3. register once, in onCreate
  4. a collect on a hot flow never returns
  5. one launch per flow inside the block

basics

~10 s

lifecycleScope is cancelled only at DESTROYED, so the collector outlives ON_STOP, and every onStart adds another. Launch once in onCreate and wrap the collection in repeatOnLifecycle(Lifecycle.State.STARTED), with one launch per flow.

solid answer

~40 s

`lifecycleScope` is bound to `Dispatchers.Main.immediate` and is cancelled only when the lifecycle reaches `DESTROYED`. A collector launched in `onStart` therefore survives `ON_STOP` and keeps the departures poll alive while the app is in the background, and each return to the screen launches one more: after three round trips, four collectors update the board. The fix is to launch once, in `onCreate`, and collect inside `repeatOnLifecycle(Lifecycle.State.STARTED)`, which cancels on `ON_STOP` and relaunches on `ON_START`. Calling `repeatOnLifecycle` itself from `onStart` recreates the duplication. Inside its block, give each flow its own `launch`: a `collect` on a hot flow never returns, so a second sequential `collect` is never reached. For a single flow, `flowWithLifecycle` does the same job.

code

kotlin · 11 lines
kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_departures)
    lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            launch { viewModel.departures.collect { board.show(it) } }
            launch { viewModel.delays.collect { banner.show(it) } }
        }
        // Not reached while the Activity is alive.
    }
}

go deeper

for a junior

Remember that lifecycleScope only ends at destruction, so collecting a flow there needs repeatOnLifecycle to stop when the screen is hidden.

for a middle

Explain why launching from onStart multiplies collectors, and why each flow needs its own launch inside repeatOnLifecycle.

for a senior

Diagnose background polling and duplicate updates from the code alone, place the fix in onCreate, and reason about flowWithLifecycle's operator order.

for a principal

Standardise one collection pattern for View-based screens, launched once and gated on STARTED, so reviewers can spot deviations at a glance.

## The symptom A ferry-departures screen polls a departures endpoint through a `Flow` and shows the results on a board. Two bugs appear in testing: the network log shows polling continuing while the app is in the background, and after the user leaves and returns a few times, the board flickers because it receives the same update several times. The screen's code looks harmless: ```kotlin override fun onStart() { super.onStart() lifecycleScope.launch { viewModel.departures.collect { board.show(it) } } } ``` ## Cause 1: lifecycleScope lives until DESTROYED `LifecycleOwner.lifecycleScope` is the owner's `Lifecycle.coroutineScope`: a `SupervisorJob` plus `Dispatchers.Main.immediate`, cancelled **only when the lifecycle reaches `DESTROYED`**. Nothing in it reacts to `ON_STOP`. A coroutine launched there runs while the Activity is stopped, so the `collect` keeps the departures flow subscribed and its upstream keeps polling. ## Cause 2: one more collector per onStart `onStart` runs every time the screen becomes visible. Each call launches a new coroutine into the same long-lived scope, and none of the earlier ones were cancelled: | Visit | onStart calls so far | Live collectors | |---|---|---| | first open | 1 | 1 | | after 1st return | 2 | 2 | | after 3rd return | 4 | 4 | Every collector calls `board.show`, hence duplicate updates, and every collector keeps its own subscription upstream. ## The fix 1. **Launch once**, from `onCreate` (or `onViewCreated` for a Fragment, using the view's lifecycle owner, which the Fragment lifecycle material covers). 2. **Gate the work** with `repeatOnLifecycle(Lifecycle.State.STARTED)`, which launches its block on `ON_START` and cancels it on `ON_STOP`. 3. **One `launch` per flow** inside the block. ```kotlin override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.departures.collect { board.show(it) } } launch { viewModel.delays.collect { banner.show(it) } } } } } ``` The `repeatOnLifecycle` KDoc names this as best practice: call it when the lifecycle is initialized, such as `onCreate` in an Activity or `onViewCreated` in a Fragment, "otherwise, multiple repeating coroutines doing the same could be created". Lifecycle 2.4 also introduced a lint check, `RepeatOnLifecycleWrongUsage`, aimed at calls from `onStart()` or `onResume()`. ## Traps inside the block - **Sequential collects.** Writing `departures.collect { }` followed by `delays.collect { }` in the same block never reaches the second line: collecting a `StateFlow` or `SharedFlow` does not complete. Each flow needs its own `launch`. - **Code after `repeatOnLifecycle`.** The call suspends until the lifecycle is `DESTROYED`, so statements after it in the same coroutine do not run while the screen is alive. - **`flowWithLifecycle` and operator order.** For a single flow, `departures.flowWithLifecycle(lifecycle).collect { }` is equivalent; `minActiveState` defaults to `STARTED`. It cancels only what is *upstream* of it: `a.flowWithLifecycle(lifecycle).combine(b)` keeps combining with `b` while stopped, whereas `a.combine(b).flowWithLifecycle(lifecycle)` stops both. For several flows, the KDoc recommends `repeatOnLifecycle` with one `launch` each, because `flowWithLifecycle` creates a hot flow per call. ## The same bug in other shapes - **`repeatOnLifecycle` called from `onStart`.** Each call suspends until `DESTROYED` and registers its own observer, so the repeating coroutines pile up exactly like the plain `launch` version, only better hidden. - **`launchWhenStarted` from `onCreate`.** It runs once, but its collector is merely paused while stopped, so the upstream can keep polling: the background half of the bug without the duplicates. - **A Fragment collecting for its views on its own lifecycle.** Launched from `onViewCreated` into the Fragment's scope, collectors pile up each time the view is destroyed and recreated while the Fragment lives; collecting on the view's lifecycle avoids that. ## Verifying the fix - Put the Activity in the background and watch the network log: polling should stop at `ON_STOP`, not at destruction. - Return to the screen several times and count `board.show` calls per update: exactly one. - After `ON_START`, a `StateFlow` delivers its current value straight away, so the board is never stale on return. Whether the ViewModel's own upstream pauses when nobody collects depends on how its `StateFlow` was shared, which is covered with sharing strategies; the screen's job is only to stop collecting.

  • Could you fix it by cancelling the Job from onStart in onStop instead?
    Yes, keeping the `Job` returned by `launch` and cancelling it in `onStop` stops both bugs, and it is roughly what `repeatOnLifecycle` does for you. The library version is safer: it cannot forget a cancel, it serialises relaunches, and it stays correct when more flows are added.
  • When is flowWithLifecycle the better choice than repeatOnLifecycle?
    When exactly one flow is collected and the call reads better as an operator chain. Place it last before `collect`, because it only cancels what is upstream of it. With two or more flows, `repeatOnLifecycle` with one `launch` per flow is cheaper, since each `flowWithLifecycle` call creates its own hot flow.

  • lifecycleScope cancels its coroutines automatically on ON_STOP
  • Calling repeatOnLifecycle from onStart is fine because it cancels on stop
  • Two collect calls in one repeatOnLifecycle block run in parallel
  • Code after repeatOnLifecycle runs once the block is launched
  • flowWithLifecycle stops every operator in the chain, wherever it is placed

Assumes Lifecycle 2.11; repeatOnLifecycle and flowWithLifecycle exist since 2.4.0, the release that also added the RepeatOnLifecycleWrongUsage lint check.