In Jetpack Lifecycle, why is launchWhenStarted deprecated in favour of repeatOnLifecycle(Lifecycle.State.STARTED), and what does each do when the screen stops?
answer
- suspend versus cancel
- a pausing dispatcher
- the upstream keeps producing
- restart on every ON_START
- deprecated in Lifecycle 2.6.0
basics
~20 slaunchWhenStarted only suspends its block on a pausing dispatcher when the screen stops, so a flow's producer keeps running and wastes resources. repeatOnLifecycle(STARTED) cancels the block on ON_STOP and relaunches it on ON_START; launchWhenX is deprecated since Lifecycle 2.6.0.
solid answer
~40 s`lifecycleScope.launchWhenStarted { }` runs its block on a pausing dispatcher: when the lifecycle drops below `STARTED`, queued work waits, but the coroutine is not cancelled until `DESTROYED`. A `collect` inside it stops processing values while the producer, such as a location callback or a network poll on another dispatcher, keeps running. That is why Lifecycle 2.6.0 deprecated the `launchWhenX` and `whenX` methods. `repeatOnLifecycle(Lifecycle.State.STARTED) { }` is a suspend function: it launches the block on `ON_START`, cancels it on `ON_STOP`, launches it again on the next `ON_START`, and returns only once the lifecycle is `DESTROYED`. Cancelling unsubscribes the upstream, so a stopped departures screen does no work. For one-time, non-suspending work, the `whenX` deprecations point to `withStarted { }`.
code
kotlin · 11 lines// Deprecated since Lifecycle 2.6.0: suspends on ON_STOP, upstream keeps running
lifecycleScope.launchWhenStarted {
viewModel.departures.collect { board.show(it) }
}
// Replacement: cancelled on ON_STOP, relaunched on ON_START
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.departures.collect { board.show(it) }
}
}go deeper
Know that lifecycleScope.launch alone runs until the screen is destroyed, and that repeatOnLifecycle(STARTED) is the standard way to collect only while visible.
Explain suspend versus cancel: the pausing dispatcher behind launchWhenStarted, cancellation on ON_STOP and relaunch on ON_START in repeatOnLifecycle, and the 2.6.0 deprecation.
Trace the wasted work: a registered location callback or network poll that outlives the visible screen under launchWhenStarted, and how cancellation unsubscribes it.
Set a lint-backed rule to migrate launchWhenX call sites to repeatOnLifecycle or withStarted, checking each for one-shot versus repeating intent.
## Two ways to tie a coroutine to visibility A ferry-departures screen should collect its live departures `Flow` only while it is visible. The Jetpack Lifecycle library has offered two families of helpers for that, and only one of them is still recommended. - **`LifecycleCoroutineScope.launchWhenStarted`** (with `launchWhenCreated`, `launchWhenResumed`, and the suspend `whenStarted` family): launches in `lifecycleScope` and runs the block only while the lifecycle is at least the given state. - **`repeatOnLifecycle(state) { }`**, on `Lifecycle` and `LifecycleOwner`: a suspend function that runs the block in a new coroutine each time the lifecycle reaches `state`. The difference is what happens when the screen stops. ## What launchWhenStarted actually does Under the hood, `launchWhenStarted` calls `whenStateAtLeast`, which runs the block on an internal **pausing dispatcher** controlled by a lifecycle observer: 1. While the lifecycle is at least `STARTED`, the dispatcher runs work normally. 2. When it falls below `STARTED` (on `ON_STOP`), the dispatcher **pauses**: continuations queue up instead of running. The coroutine is **suspended, not cancelled**. 3. On the next `ON_START` the queue drains and the block carries on where it was. 4. Only `DESTROYED` cancels the job. For a `collect`, step 2 means the collector stops handling values, but nothing tells the upstream to stop. A `callbackFlow` wrapping location updates stays registered, a polling flow running on another dispatcher keeps polling, and a buffered channel keeps filling. The library's documentation also notes that sub-coroutines on a different dispatcher are not affected by the pause at all. The deprecation message says it plainly: *launchWhenStarted is deprecated as it can lead to wasted resources in some cases*; the `whenX` messages add that the dispatcher *suspends, rather than cancels work*. ## What repeatOnLifecycle does instead `repeatOnLifecycle(Lifecycle.State.STARTED) { ... }` registers an observer and uses the state graph: | Event | Effect on the block | |---|---| | `Event.upTo(STARTED)` = `ON_START` | launches the block in a new child coroutine | | `Event.downFrom(STARTED)` = `ON_STOP` | **cancels** that coroutine | | `ON_DESTROY` | the function resumes and returns | Key properties from its source and KDoc: - It **suspends the caller until `DESTROYED`**, so code after it in the same coroutine does not run while the screen is alive. - Each relaunch waits for the previous run to finish, so invocations of the block are **serial**. - Passing `Lifecycle.State.INITIALIZED` throws `IllegalArgumentException`; if the lifecycle is already `DESTROYED`, it returns at once. - It runs its observer on `Dispatchers.Main.immediate` but launches the block preserving the caller's context. Because the block is cancelled, `collect` is cancelled too, and cancellation reaches the upstream: a `callbackFlow` runs its `awaitClose` cleanup, which is where a location callback is removed, and a polling loop stops at its next suspension point. On the next `ON_START` the block runs from the top and collects afresh; a `StateFlow` hands over its latest value immediately, while a cold flow starts again from the beginning. ## flowWithLifecycle and withStarted - **`Flow.flowWithLifecycle(lifecycle, minActiveState)`** wraps one flow in `repeatOnLifecycle`. `minActiveState` defaults to `Lifecycle.State.STARTED`. It is an intermediate operator, so it is still followed by `collect`. - **`Lifecycle.withStarted { }`** (and `withCreated`, `withResumed`, `withStateAtLeast`) runs a *non-suspending* block once the lifecycle reaches the state, and throws `LifecycleDestroyedException` if it is destroyed first. The `whenX` deprecations point here for one-shot work. ## Migrating existing call sites Each `launchWhenX` call hides an intent that has to be recovered before it can be replaced: 1. **Repeating collection** (a `collect` that should follow visibility): wrap it in `lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { ... } }`, launched once from `onCreate`. 2. **One-time UI action** (show a dialog once the screen is started): use `lifecycle.withStarted { }`, which keeps the non-suspending block safe from running while stopped. 3. **Suspending one-shot work** (a request whose result updates the screen): the Lifecycle release notes call one-time suspending work tied to a screen's state inherently unsafe; start it in a longer-lived owner such as a ViewModel and let the screen observe the result with `repeatOnLifecycle`. Watch for behaviour that silently changes during migration: - A cold flow restarts from scratch at every `ON_START`, which can repeat network calls that the paused version did not repeat. - `try`/`finally` cleanup now runs at every `ON_STOP`, not only at destruction. ## Versions `repeatOnLifecycle` and `flowWithLifecycle` arrived in Lifecycle 2.4.0. The `launchWhenX` and `whenX` methods were deprecated in 2.6.0 and remain deprecated in 2.11. Since 2.8.0, `repeatOnLifecycle` and `flowWithLifecycle` ship in `lifecycle-runtime` itself, and the old `lifecycle-runtime-ktx` artifact is empty. In Compose, the equivalent collection helper is covered with Compose state.
- The departures flow is a StateFlow from a ViewModel. Does the collector see stale data after ON_START?No. When `repeatOnLifecycle` relaunches the block, `collect` subscribes again and a `StateFlow` delivers its current value at once, so the board shows the latest departures rather than whatever was last drawn. Whether the ViewModel's upstream itself stopped while nobody collected depends on how that `StateFlow` was shared, which is a sharing-strategy question.
- When would you still need a one-time lifecycle-gated call, and what replaces whenStarted for it?For something like showing a dialog only once the screen is started, use `lifecycle.withStarted { }`. It runs a non-suspending block once the lifecycle is at least `STARTED` and throws `LifecycleDestroyedException` if the lifecycle is destroyed first. Long-running or suspending work belongs in `repeatOnLifecycle`.
- Why does repeatOnLifecycle reject Lifecycle.State.INITIALIZED?It starts work on `Event.upTo(state)` and stops on `Event.downFrom(state)`. No event moves a lifecycle up to `INITIALIZED`, so there is nothing to start on; the function checks the argument with `require` and throws `IllegalArgumentException`.
launchWhenStarted is like pausing a film while the projector keeps running and burning its bulb; repeatOnLifecycle switches the projector off at ON_STOP and starts the reel again at ON_START.
- launchWhenStarted cancels the coroutine when the screen stops
- repeatOnLifecycle returns as soon as its block has been launched
- Pausing the collector also pauses the upstream producer
- launchWhenStarted is still the recommended API in Lifecycle 2.11
- flowWithLifecycle is a terminal operator that collects the flow
Assumes Lifecycle 2.11; launchWhenX and whenX are deprecated since 2.6.0, and repeatOnLifecycle and flowWithLifecycle exist since 2.4.0.