Consuming flows safely in Jetpack Compose
<p>Collecting flows in a lifecycle-aware manner is the <a href="https://developer.android.com/topic/architecture/ui-layer#consume-ui-state" rel="noopener ugc nofollow" target="_blank">recommended way</a> to collect flows on Android. If you’re building an Android app with Jetpack Compose, use the <code>collectAsStateWithLifecycle</code> API to collect flows in a lifecycle-aware manner from your UI.</p>
<p><code>collectAsStateWithLifecycle</code> 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.</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 <code>collectAsState</code> API.</p>
<h1>collectAsStateWithLifecycle</h1>
<p><code>collectAsStateWithLifecycle</code> is a composable function that collects values from a flow and represents the latest value as Compose <code><a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/State" rel="noopener ugc nofollow" target="_blank">State</a></code> in a lifecycle-aware manner. Every time a new flow emission occurs, the value of this <code>State</code> object updates. This causes a recomposition of every <code>State.value</code> usage in the Composition.</p>
<p>By default, <code>collectAsStateWithLifecycle</code> uses <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> 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 <code>minActiveState</code> parameter.</p>
<p><a href="https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3">Read More</a></p>