Architecture components ViewModel vs. savedInstanceState bundle

只谈情不闲聊 提交于 2019-12-12 08:29:13

问题


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.




回答2:


If someone is still looking to understand difference between onSavedState vs ViewModel here is the detailed explanation:

  1. onSavedInstanceState : Primary usage of onSavedInstance was not to handle orientation change but to provide a mechanism to retrieve data if app/activity is destroyed by Android System. Example case when app is in background and Android system decide to kill this as it needs memory for some other high priority process then in this case before activity is destroyed onSavedInstanceState will be called.

  2. onSavedInstanceState only stores the Parcelable data, that provides hint to restore the state for the user when activity restarts. It saves data in System server that is a separate process.

  3. onSavedInstanceState has data limit. Only small amount of Parcelable data can be saved.

While for ViewModel

  1. ViewModel object is part of Applications process memory and hence it is able to survive configuration changes. Once a process dies, ViewModel goes away and all the saved state will be lost. Hence when activity restart ViewModel has nothing in it.

  2. It works as a cache for for heavy object.

  3. There are no restrictions in ViewModel.

Important: Always remember ViewModel and SavedState work together. They are not replacement or alternative to each other.



来源:https://stackoverflow.com/questions/45509194/architecture-components-viewmodel-vs-savedinstancestate-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!