Architecture components ViewModel vs. savedInstanc

2019-04-07 10:03发布

问题:

Trying to understand what is the difference with using the ViewModel to keep some of the state of the activity or fragment, and saving them with the savedInstanceState bundle.

Got a impression that the ViewModel instance is kept alive when the activity/fragment is destroyed by os in the case like configuration change so that when os recreate the activity/fragment could get the data from the ViewModel instance which is still valid.

Does it apply to minimize the app and re-open it?

Did some test, seems minimize the app and re-open the app, the os will recreate the activity/fragment with the stavedInstanceState bundle in the onCreate() not null (whatever is saved when the onSaveInstanceStae() is called). But the ViewModel has been cleared so a new instance is created without previous ones data.

Does it it mean although is in this case the os can retrieve the saved instance state and pass to activity/fragment's onCreate(), but the ViewModel has to be a new instance without previous instance's data, or the viewModel needs do to some extra step inorder to store/restore the data cross the instances?

回答1:

A good explanation (and a solution to your problem) can be found in this blogpost. TLDR: the viewmodel is hosted inside a persisted fragment, which gets recreated together with the hosting activity.