LiveData
LiveData
Limitation of ViewModel ?
- we cannot communicate from ViewModel back to UI Controller because we don't have the reference to it.
- ViewModel will preserve data in config changes but the data is still lost when the OS kills the app to garbage collect and free up memory when the app is in background, so we need to savetheinstance state using safeargs of navigation component or saveinstancestate.
For ex. we need the ViewModel to communicate when data like score has changed so that the game fragment knows to actually redraw the score. What would be really great is if we could change the data in the ViewModel and then just have the screen magically know when to update itself. So LiveData can do this for us.
LiveData is an observable data holder class that is also lifecycle aware.
- LiveData holds data, this means that it wraps around sub data for ex. we have LiveData wrap around the current score live.
- LiveData is also observable.
Observer Pattern
- Object called the subject
- Subject keeps track of a list of other objects known as Observers.
- Observers watch or observe the subject when the status of the subject changes it notifies the observers by calling a method in observer.
In LiveData case
- Subject is the LiveData object
- Observers are the UI Controllers
- State change is whatever the data wrapped inside the LiveData changes.
- Ex. live data and Fragment : whenever live data changes it auto calls method of Fragment
// how to use this
viewModel.livedata.observer(this, Observer { yourlivedata ->
updateUI(yourlivedata)
})
LiveData is Lifecycle Aware
- LiveData knows about its LifeCycle state of it's UI Controller observers
- LiveData uses this information to interact intelligently with your fragments and activities.
- LiveData will only update the UI Controller that are actually onscreen. So, if the fragment goes offscreen the value of UI is not updated, but only when the UI goes onscreen.
- LiveData also does it own cleanup, so we don't need to write code in onDestroy
Comments
Post a Comment