collectAsStateWithLifecycle
Collect flows safely with the lifecycle.
collectAsStateWithLifecycle is a free Android Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 4 lessons in total.
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
StateFlowandstateIn(WhileSubscribed)for an efficient pipeline.
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 36
- Lessons
- 152
Frequently Asked Questions
Is the “collectAsStateWithLifecycle” lesson free?
Yes — any 3 lessons of the Android Academy learning path, including “collectAsStateWithLifecycle”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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
- Why Use a ViewModel?
- Exposing State from ViewModel
- The Android Lifecycle
- collectAsStateWithLifecycle