In Jetpack Compose on Android, how does `collectAsStateWithLifecycle` differ from `collectAsState` when a checkout screen collects a live price-summary Flow?
answer
- one of them pauses in the background
- a separate lifecycle artifact
- repeatOnLifecycle inside a LaunchedEffect
- minActiveState defaults to STARTED
basics
~20 scollectAsState collects for as long as the composable is in the composition, even while the app sits in the background. collectAsStateWithLifecycle stops collecting when the lifecycle drops below minActiveState, STARTED by default, and resumes above it, so Android screens should prefer it.
solid answer
~40 sBoth turn a `Flow` into a Compose `State<T>` whose reads recompose when a new value arrives. `collectAsState` lives in compose-runtime and starts a collection that runs as long as the call stays in the composition, regardless of whether the activity is visible. `collectAsStateWithLifecycle`, from `androidx.lifecycle:lifecycle-runtime-compose`, runs a `LaunchedEffect` that calls `lifecycle.repeatOnLifecycle(minActiveState)`: collection is cancelled when the lifecycle falls below `minActiveState` (default `Lifecycle.State.STARTED`) and restarted when it climbs back, while the `State` keeps its last value. The `StateFlow` overload uses the flow's current `value` as the initial value; a plain `Flow` needs `initialValue`. The lifecycle defaults to `LocalLifecycleOwner.current`. For a price summary fed by a repository, that means no work while the app is in the background, which is why Android's guidance recommends it for collecting flows in Compose.
code
kotlin · 18 linesimport androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.StateFlow
data class PriceSummary(val totalCents: Long, val discountCents: Long)
@Composable
fun CheckoutTotals(summaryFlow: StateFlow<PriceSummary>) {
val summary by summaryFlow.collectAsStateWithLifecycle()
TotalsRow(totalCents = summary.totalCents, discountCents = summary.discountCents)
}
@Composable
fun TotalsRow(totalCents: Long, discountCents: Long) {
Text("Total ${totalCents / 100}.${"%02d".format(totalCents % 100)} (saved ${discountCents / 100})")
}go deeper
Recall which API to use on Android screens and the artifact it comes from, and that the State keeps the last value while collection is paused.
Explain the mechanism: a LaunchedEffect running repeatOnLifecycle with minActiveState STARTED, the initial-value rules for StateFlow and Flow, and LocalLifecycleOwner as the default owner.
Diagnose background work and restart storms: flows created during composition, collectors in every child, or collectAsState on screens that sit behind another app.
Standardise one lifecycle-aware collection per screen at the screen-level composable, with plain values passed down, and decide when RESUMED is justified.
## Two ways to turn a Flow into State Compose recomposes when it reads **snapshot state**, so a Kotlin `Flow` has to be converted into a `State<T>` before a composable can react to it. Two extension functions do that: - `collectAsState()`, in `androidx.compose.runtime`, with no extra dependency; - `collectAsStateWithLifecycle()`, in `androidx.lifecycle:lifecycle-runtime-compose`, package `androidx.lifecycle.compose`. Both remember a `MutableState`, start a coroutine that writes each emission into it, and return it as `State<T>`. Reading the result with `by` subscribes the reading scope, so the price-summary text recomposes when a new total arrives. ## What `collectAsState` does `collectAsState` launches its collection from the composition and cancels it only when the call leaves the composition or the flow instance or `context` changes. The activity going to the background does **not** remove the composition, so a checkout screen that the user has left behind another app keeps collecting: database queries, network polling or price recalculation upstream keep running for a screen nobody is looking at. Its `context` parameter defaults to `EmptyCoroutineContext`; passing a different context runs the collection inside `withContext(context)`, which only changes where `collect` runs, not when it stops. The same parameter exists on the lifecycle-aware version. That is not a crash risk. Writing a `MutableState` while the app is in the background is safe; Compose simply renders the change when the UI is visible again. The cost is wasted work and battery. ## What `collectAsStateWithLifecycle` adds Internally it runs `LaunchedEffect(flow, lifecycle, minActiveState, context)` and inside it `lifecycle.repeatOnLifecycle(minActiveState) { collect { state.value = it } }`. 1. When the lifecycle reaches `minActiveState`, collection starts. 2. When the lifecycle falls below it, for example on `ON_STOP` with the default `STARTED`, the collecting coroutine is cancelled. 3. When the lifecycle reaches the state again, collection restarts from scratch. 4. Throughout, the returned `State` keeps the last value it received; nothing is reset. For a `StateFlow`, the overload reads the flow's current `value` as the initial value during composition, so the first frame already shows the latest total instead of a placeholder. Because collection really stops, an upstream that only produces while it has subscribers can stop producing too; how a shared or state flow decides that belongs to the Kotlin Flow material. | | `collectAsState` | `collectAsStateWithLifecycle` | |---|---|---| | Artifact | compose-runtime | lifecycle-runtime-compose | | Stops when | the call leaves the composition | lifecycle below `minActiveState`, or leaves the composition | | Default threshold | none | `Lifecycle.State.STARTED` | | Lifecycle source | none | `LocalLifecycleOwner.current` by default | | Initial value | `StateFlow.value`, or `initial` for a `Flow` | `StateFlow.value`, or `initialValue` for a `Flow` | ## Choosing the threshold and the owner - **`STARTED`** (the default) keeps updating while the screen is visible, even if it is partially covered and not resumed. - **`RESUMED`** narrows collection to when the screen is in the foreground and interactive. - **`CREATED`** keeps collecting while stopped, which is rarely what you want. - **`INITIALIZED`** is not allowed and throws `IllegalArgumentException`. - The `lifecycleOwner` parameter defaults to `LocalLifecycleOwner.current`. Navigation libraries provide each destination with its own owner, so the destination's lifecycle, not only the activity's, decides when collection runs. ## Common mistakes - Calling `collectAsState` on Android screens out of habit and wondering why upstream work continues in the background. - Expecting the `State` to clear or show a loading value when collection restarts; it keeps the last value until the flow emits again. - Building the flow inside the composable, as in `repository.totals().map { ... }.collectAsStateWithLifecycle(0L)`, which creates a new `Flow` instance on every recomposition and restarts the collection each time. Create the flow once, outside composition or in `remember`. - Collecting the same flow in several small composables instead of once at the screen level and passing the value down. ## Where it fits on the checkout screen The screen-level composable collects the price-summary flow once, `val summary by summaryFlow.collectAsStateWithLifecycle()`, and passes plain values such as `summary.totalCents` to stateless children. That keeps one lifecycle-aware subscription per screen and leaves the children free of any knowledge of flows.
- Why does `collectAsStateWithLifecycle` need an `initialValue` for a plain `Flow` but not for a `StateFlow`?The returned `State` must hold a value before the first emission arrives, and a plain `Flow` has no current value to read. A `StateFlow` always has one, so its overload uses `value` as the starting state.
- What happens if you pass `minActiveState = Lifecycle.State.INITIALIZED`?It throws `IllegalArgumentException`; the function's documentation lists `INITIALIZED` as not allowed. Use `CREATED`, `STARTED` or `RESUMED`, and keep the default `STARTED` unless there is a reason to narrow or widen it.
- Is it a bug to write to a `MutableState` while the app is in the background?No. Compose accepts state writes at any time and renders them when the UI is visible again. The reason to prefer the lifecycle-aware collector is the upstream work it stops, not a crash it prevents.
- collectAsState crashes if the flow emits while the app is in the background
- collectAsStateWithLifecycle ships in compose-runtime with no extra dependency
- The State resets to its initial value when collection stops
- minActiveState defaults to RESUMED
- Lifecycle-aware collection means the flow keeps running but recomposition pauses