Search code examples
androidandroid-jetpack-composestate-management

Difference between observeAsState and collectAsState and when to use each in Android Jetpack Compose?


I am learning Jetpack Compose but facing some issues in understanding states. Can someone explain these two? observeAsState and collectAsState. Thank you.


Solution

    1. observeAsState is an extension on LiveData.
      Starts observing this LiveData and represents its values via State.
      Uses Lifecyle internally for safely observing the data.

    2. 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.