Home
+91 99674 50288
info@appmonks.net
×

LiveData In Android



LiveData is an observable data holder class. 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.


LiveData considers an observer, which is represented by the observer class, to be in an active state if its lifecycle is in the start or resume state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.

You can register an observer paired with an object that implements the LifeCycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to Destroyed.

This is especially useful for activities and fragments because they can safely observe LiveData objects and not worry about leaks activities and fragments are instantly unsubscribed when their lifecycles are destroyed.


THE ADVANTAGES OF USING LIVEDATA ARE AS FOLLOWS :


1. Ensures your UI matches your data state 

LiveData follows the observer pattern. LiveData notifies observers objects when the lifecycle state changes. You can consolidate your code to update the UI in these observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there's a change.

2. No memory leaks

Observers are bound to LifeCycle objects and clean up after themselves when their associated lifecycle is destroyed.

3. No crashes due to stopped activities

If the observer's lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

4. No more manual lifecycle handling

UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.

5. Always up to date data

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

6. Proper configuration changes

If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

7. Sharing resources

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extended LiveData. 

Mail
casino