架构组件 ViewModel vs. savedInstanceState 包 [英] Architecture components ViewModel vs. savedInstanceState bundle

查看:26
本文介绍了架构组件 ViewModel vs. savedInstanceState 包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解使用 ViewModel 保留 Activity 或 Fragment 的某些状态并使用 savedInstanceState 包保存它们的区别.

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.

印象中,当活动/片段被操作系统销毁时,在配置更改等情况下,ViewModel 实例会保持活动状态,以便在操作系统重新创建活动/片段时,可以从仍然有效的 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 包重新创建活动/片段不为空(调用 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?

推荐答案

可以在 在这篇博文中.TLDR:视图模型托管在持久片段中,该片段与托管活动一起重新创建.

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 vs. savedInstanceState 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆