ViewModel and LiveData
Both ViewModel
and LiveData
represent specialized implementations of the life cycle mechanisms. They come in handy in situations where you want to keep your data saved when the screen rotates and when you want your data to be displayed only when the Views are available, thus avoiding one of the most common issues developers face – a NullPointerException
– when trying to update a View. A good use of this is when you want to display the live score of your favorite team's game and the current minute of the game.
ViewModel
The ViewModel
component is responsible for holding and processing data required by the UI. It has the benefit of surviving configuration changes that destroy and recreate fragments and activities, which allows it to retain the data that can then be used to re-populate the UI. It will be eventually destroyed when the activity or fragment will be destroyed without being recreated or when the application process is terminated...