Ravi
Ravi

Reputation: 2367

Do we still need onSaveInstanceState() when we have ViewModels?

Now with the View model as we can handle the configuration changes and manage the UI data, So the onSaveInstance() I feel now if of no use for me.

Like earlier we used to store smaller data onSaveInstanceState() and used to restore it during configuration, now using view model we can easily get the updated data. So could you please tell me whats the actual usage of onSaveInstanceState() and onRestoreInstancestate() now if we are using ViewModel.

Could you please tell me the usage of it in the current case with ViewModel

Upvotes: 4

Views: 1232

Answers (1)

iCantC
iCantC

Reputation: 3180

Data can still be lost when Android OS decides to kill your application process due to memory constraints and then later re-create it. This is different from Configuration changes.

ViewModel successfully saves your data from the configuration change (Activity/Fragment Recreation), but it won't be of much help in case of Process Recreation.

In order to persist data even in case of Process Recreation, you will need to use onSaveInstanceState().

However with recent updates, by means of SavedStateHandle ViewModel directly allows you to save instance state, which will automatically survive process death/recreation. This implies, you no more need to use onSaveInstanceState of your Activity/Fragment to persist data across process death, just use SavedStateHandle in your ViewModel, it will act the same.

Upvotes: 9

Related Questions