Android Architecture Components provide the LiveData
and ViewModel
classes which are more lifecycle-friendly and designed for a leaner Activity/Fragment. These classes handle storing data across configuration changes, but I'm confused about their use compared to the Activity framework APIs. Are onSaveInstanceState(Bundle)
and onRestoreInstanceState(Bundle)
still necessary or useful for preserving activity state?
Why should you initialize and store LiveData in your ViewModel instead of a UI Controller? Both the ViewModel and LiveData are lifecycle aware. To ensure that the LiveData isn't destroyed when the UI Controller is destroyed. To hide or separate implementation details making your app more flexible.
UI state is usually stored or referenced in ViewModel objects and not activities, so using onSaveInstanceState() requires some boilerplate that the saved state module can handle for you.
ViewModel objects are automatically retained (they are not destroyed like the activity or a fragment instance) during configuration changes so that data they hold is immediately available to the next activity or fragment instance.
Unlike saved instance state, ViewModels are destroyed during a system-initiated process death.
onSaveInstanceState & onRestoreInstanceState is still useful.
ViewModel holds data only when process is alive.
But, onSaveInstanceState & onRestoreInstanceState can hold data even if process is killed.
ViewModel is easy to use and useful for preserving large data when screen orientation changes.
onSaveInstanceState & onRestoreInstanceState can preserve data when process is in background.(in background, app process can be killed by system at anytime.)
Assume a scenario :
user is in activity A
, then navigates to activity B
but because of low memory Android OS destroys activity A
, therefor the ViewModel
connected to it also destroys. (You can emulate it by checking Don't keep activities
in Developer options)
now user navigates back to activity A
, Android OS try's to create new Acivity
and ViewModel
objects. therefor you loosed data in ViewModel
.
But still values in savedInstanceState are there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With