Consuming flows safely in Jetpack Compose

<p>Collecting flows in a lifecycle-aware manner is the&nbsp;<a href="https://developer.android.com/topic/architecture/ui-layer#consume-ui-state" rel="noopener ugc nofollow" target="_blank">recommended way</a>&nbsp;to collect flows on Android. If you&rsquo;re building an Android app with Jetpack Compose, use the&nbsp;<code>collectAsStateWithLifecycle</code>&nbsp;API to collect flows in a lifecycle-aware manner from your UI.</p> <p><code>collectAsStateWithLifecycle</code>&nbsp;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&rsquo;s device health. Such resources may include firebase queries, location or network updates, and database connections.</p> <p>Keep reading to know more about this API, why you should collect in a lifecycle-aware manner, and how it compares to the&nbsp;<code>collectAsState</code>&nbsp;API.</p> <h1>collectAsStateWithLifecycle</h1> <p><code>collectAsStateWithLifecycle</code>&nbsp;is a composable function that collects values from a flow and represents the latest value as Compose&nbsp;<code><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/State" rel="noopener ugc nofollow" target="_blank">State</a></code>&nbsp;in a lifecycle-aware manner. Every time a new flow emission occurs, the value of this&nbsp;<code>State</code>&nbsp;object updates. This causes a recomposition of every&nbsp;<code>State.value</code>&nbsp;usage in the Composition.</p> <p>By default,&nbsp;<code>collectAsStateWithLifecycle</code>&nbsp;uses&nbsp;<code><a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.State#started" rel="noopener ugc nofollow" target="_blank">Lifecycle.State.STARTED</a></code>&nbsp;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&nbsp;<code>minActiveState</code>&nbsp;parameter.</p> <p><a href="https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3">Read More</a></p>