collectWithLifecycle

inline fun <T> LifecycleOwner.collectWithLifecycle(flow: Flow<T>, crossinline action: (T) -> Unit)

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 prevents unnecessary work and memory leaks.

Usage in Fragment

class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

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 pauses when lifecycle falls below STARTED (e.g., app backgrounded)

  • Collection resumes when lifecycle reaches STARTED again

  • Collection stops permanently when lifecycle is DESTROYED

Parameters

T

The type of data emitted by the Flow

flow

The Flow to collect

action

Callback invoked with each non-null emitted value

See also