-
LiveData is part of the Lifecycle library which was designed to help solve common Android Lifecycle challenges.
-
Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components,such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
-
For example, if livedata in ViewModel was changed, only when activity is active status(on screen), including
- after onStart(), STARTED state
- after onResume(), RESUMED/RUNNING state
- after onPause(), but before onStop()
- LiveData is not designed to handle asynchronous streams of data. Even though you can use LiveData transformations and MediatorLiveData to achieve this. this approach has drawbacks: the capability to combine streams of data is very limited and all LiveData objects are observed on the main thread, this probably can block the main thread
- If we need to use LiveData in other layer, can just consider using kotlin flow and then converting them to LiveData in the ViewModel using asLiveData().
- If want to make changes to the value stored in a LiveData object before dispatching it to the observers, or you may need to return a different LiveData instance based on the value of another one.