架构组件ViewModel与SavedInstanceState捆绑包 [英] Architecture components ViewModel vs. savedInstanceState bundle
问题描述
试图了解使用ViewModel保留活动或片段的某些状态,然后将它们与saveInstanceState包保存在一起有什么区别.
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.
给人一种印象,当在配置更改之类的情况下os破坏了活动/片段时,ViewModel实例仍处于活动状态,因此当os重新创建活动/片段时,可以从仍然有效的ViewModel实例获取数据.
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?
进行了一些测试,似乎最小化了应用程序,然后重新打开了应用程序,操作系统将使用onCreate()中的stavedInstanceState包重新创建活动/片段(不保存为null)(调用onSaveInstanceStae()时将保存所有内容).但是ViewModel已清除,因此可以创建一个没有先前数据的新实例.
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.
这是否意味着,尽管在这种情况下,操作系统可以检索保存的实例状态并传递给活动/片段的onCreate(),但是ViewModel必须是没有先前实例数据的新实例,否则viewModel需要这样做一些额外的步骤以便跨实例存储/恢复数据?
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?
推荐答案
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.
这篇关于架构组件ViewModel与SavedInstanceState捆绑包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!