I am learning Jetpack Compose but facing some issues in understanding states. Can someone explain these two? observeAsState and collectAsState. Thank you.
observeAsState
is an extension on LiveData
.
Starts observing this LiveData
and represents its values via State
.
Uses Lifecyle
internally for safely observing the data.
collectAsState
is an extension on StateFlow
.
Collects values from this StateFlow
and represents its latest value via State.
You need to handle the collection as per appropriate Lifecyle
.
Source: Compose#LiveData & Compose#Flow .
An addition of Darshan´s answer is that in version 2.6.0-alpha.1 we have a new extension function that takes care of lifecylce when collecting StateFlow.
Link of release notes: https://developer.android.com/jetpack/androidx/releases/lifecycle?hl=es-419#2.6.0-alpha01
Example of use. https://medium.com/tech-takeaways/how-to-safely-collect-flows-lifecycle-aware-in-jetpack-compose-a-new-approach-ed20ead25be9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.