0Pricing
Android Academy · Lesson

collectAsStateWithLifecycle

Collect flows safely with the lifecycle.

collectAsStateWithLifecycle is a free Android Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Collecting Flows Safely

When a Composable collects a flow, it should ideally stop collecting while the screen is in the background and resume when it returns.

The tool for this is collectAsStateWithLifecycle().

The Problem with collectAsState

Plain collectAsState() keeps collecting as long as the Composable is in the composition — even when the app is in the background.

This can waste resources and process updates the user cannot see.

Enter collectAsStateWithLifecycle

This lifecycle-aware collector pauses collection when the lifecycle drops below a target state (STARTED by default) and resumes when it returns.

import androidx.lifecycle.compose.collectAsStateWithLifecycle

@Composable
fun Screen(vm: MyViewModel) {
    val state by vm.uiState
        .collectAsStateWithLifecycle()
    Text(state.title)
}

The Dependency

It lives in the androidx.lifecycle:lifecycle-runtime-compose artifact. Add it to your module so the import resolves.

// build.gradle (module)
implementation(
  "androidx.lifecycle:lifecycle-runtime-compose:2.x.x"
)

Default Minimum State: STARTED

By default, collection is active while the lifecycle is at least STARTED — meaning the screen is visible. When it goes to the background (below STARTED) collection is suspended.

Customizing the Minimum State

You can change the threshold with minActiveState, for example to RESUMED.

val state by vm.uiState.collectAsStateWithLifecycle(
    minActiveState = Lifecycle.State.RESUMED
)

Pairing with StateFlow

This works perfectly with the StateFlow you expose from a ViewModel. The flow always has a current value, so re-collection instantly shows the latest state.

private val _uiState = MutableStateFlow(UiState())
val uiState = _uiState.asStateFlow()

Why It Saves Work

If your flow drives expensive computation (filtering a large list, transforming streams), suspending collection in the background means that work simply does not run while the user is away.

Combining with viewModelScope

On the producer side, the ViewModel often runs its data pipeline in viewModelScope. With stateIn you can even make the upstream stop when there are no collectors.

val uiState = repository.stream()
    .stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = UiState()
    )

WhileSubscribed Explained

WhileSubscribed(5000) keeps the upstream alive for 5 seconds after the last collector leaves. This avoids restarting work during brief config changes while still stopping it when the user truly leaves.

Best Practice Summary

For Compose screens backed by a ViewModel:

  • Expose a StateFlow.
  • Collect with collectAsStateWithLifecycle().
  • Optionally use stateIn(WhileSubscribed) upstream.

Quick Check

Test your understanding of lifecycle-aware collection.

Recap

You learned:

  • collectAsStateWithLifecycle() pauses collection in the background.
  • Default threshold is STARTED, adjustable via minActiveState.
  • Pair it with a StateFlow and stateIn(WhileSubscribed) for an efficient pipeline.

Frequently asked questions

Is the “collectAsStateWithLifecycle” lesson free?

Yes — the full text of “collectAsStateWithLifecycle” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “collectAsStateWithLifecycle”?

Collect flows safely with the lifecycle. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “collectAsStateWithLifecycle” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why Use a ViewModel?
  2. Exposing State from ViewModel
  3. The Android Lifecycle
  4. collectAsStateWithLifecycle
← Back to Android Academy