Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any need to use onSaveInstanceState and onRestoreInstanceState when using Android Architecture Components LiveData & ViewModel?

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?

like image 688
Zeatual Chang Avatar asked Jun 15 '17 07:06

Zeatual Chang


People also ask

Why should you initialize and store LiveData in your ViewModel instead of a UI controller?

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.

How UI state is managed with ViewModel?

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.

How does ViewModel retain data?

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.

Does ViewModel survive process death?

Unlike saved instance state, ViewModels are destroyed during a system-initiated process death.


2 Answers

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.)

like image 195
UnknownStack Avatar answered Oct 04 '22 01:10

UnknownStack


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.

like image 26
Mojtaba Haddadi Avatar answered Oct 04 '22 02:10

Mojtaba Haddadi