Understanding Android components’ background
In many situations, you must use onSaveInstanceState to save the current state of your activity or fragment, and then, in onCreate or onRestoreInstanceState, you need to restore the state of your activity or fragment. This adds extra complexity to your code and makes it repetitive, especially if the processing code is part of your activity or fragment.
These scenarios are where ViewModel and LiveData come in. ViewModel components are built with the express goal of holding data in case of life cycle changes. They also separate the logic from views, which makes them very easy to unit test. LiveData is a component used to hold data and notify observers when changes occur while taking their life cycle into account.
In simpler terms, the fragment only deals with views, ViewModel does the heavy lifting, and LiveData deals with delivering the results to the fragment, but only when the fragment is there and ready.
If you’...