Android components background
In many situations, you have to use onSaveInstanceState
to save the current state of your activity/fragment, and then in onCreate
or onRestoreInstanceState
, you need to restore the state of your activity/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. ViewModels
are components built with the express goal of holding data in case of lifecycle changes. They also separate the logic from the 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 lifecycle into account.
In simpler terms, the fragment only deals with the 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’ve ever used WhatsApp...