Christophe Beyls
1 min readOct 8, 2022

--

That's an excellent question and I should probably add a paragraph about Jetpack Compose in the article.

Short answer: No matter the view system you use, Flows are consumed in exactly the same manner from the ViewModel and you should always consider making your Flows more efficient between recollections because of the Android Lifecycle. All the ViewModel implementations I show in the article work exactly the same way with Views or with Compose.

Long answer: Compose State is very similar to StateFlow and is not Lifecycle-aware by itself. To make a Compose State Lifecycle-aware, you need to connect it to a data source using either LiveData.observeAsState() or the new Flow.collectAsStateWithLifecycle(). Both these composable extension functions will use the LocalLifecycleOwner by default to retrieve the current Lifecycle and make sure the source LiveData or Flow is only observed/collected while the screen is visible.

Manuel Vivo from Google recently wrote an article about Flow.collectAsStateWithLifecycle(): https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

No responses yet