collectWithLifecycle
Collects a Flow in a lifecycle-aware manner, automatically canceling when lifecycle stops.
This extension collects the Flow when the lifecycle is at least STARTED and automatically cancels collection when the lifecycle falls below STARTED. This restarts collection on a later STARTED transition. Separately launched upstream jobs have their own lifetimes; this helper does not cancel those jobs. In a Fragment, use viewLifecycleOwner when updating its views.
Illustrative Fragment usage (ViewModel and binding supplied by the caller)
class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.collectWithLifecycle(viewModel.uiState) { state ->
binding.progressBar.isVisible = state.loading
binding.errorText.text = state.error
}
}
}Multiple Flows
collectWithLifecycle(viewModel.uiState) { state ->
updateUI(state)
}
collectWithLifecycle(viewModel.events) { event ->
handleEvent(event)
}In Compose (Alternative)
For Composables, use collectAsStateWithLifecycle() instead:
@Composable
fun MyScreen(viewModel: MyViewModel = hiltViewModel()) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
// Use uiState...
}Lifecycle Behavior
Collection starts when lifecycle reaches STARTED
Collection is cancelled when lifecycle falls below STARTED (e.g., app backgrounded)
A new collection starts when lifecycle reaches STARTED again
Collection stops permanently when lifecycle is DESTROYED
Parameters
The Flow to collect
Callback invoked with each non-null emitted value
Type Parameters
The type of data emitted by the Flow