Collecting flows in a lifecycle-aware manner is the recommended way to collect flows on Android. If you’re building an Android app with Jetpack Compose, use the collectAsStateWithLifecycle API to collect flows in a lifecycle-aware manner from your UI.
collectAsStateWithLifecycle allows your app to save app resources when not needed, such as when the app is in the background. Keeping resources alive unnecessarily can impact the user’s device health. Such resources may include firebase queries, location or network updates, and database connections.
Keep reading to know more about this API, why you should collect in a lifecycle-aware manner, and how it compares to the collectAsState API.
collectAsStateWithLifecycle
collectAsStateWithLifecycle is a composable function that collects values from a flow and represents the latest value as Compose State in a lifecycle-aware manner. Every time a new flow emission occurs, the value of this State object updates. This causes a recomposition of every State.value usage in the Composition.
By default, collectAsStateWithLifecycle uses Lifecycle.State.STARTED to start and stop collecting values from the flow. This occurs when the Lifecycle moves in and out of the target state. This lifecycle state is something you can configure in the minActiveState parameter.