ViewModel是否可以在Activity中保存和恢复? [英] Does ViewModel survive Activity save and restore?

本文介绍了ViewModel是否可以在Activity中保存和恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以以下方式使用,新的ViewModel类的实例可以在配置更改后继续存在:

mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

但是,除了配置更改外,在终止整个应用程序的进程时,还存在保存-还原方案.

在保存-还原方案期间,是否会保留ViewModel中字段的值?


基于此问题的答案,我写了这篇文章:解决方案

根据 Android ViewModel体系结构组件很危险.

Instances of the new ViewModel class can survive configuration changes if used in the following fashion:

mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

However, in addition to configuration changes, there is also a save-restore scenario when the entire application's process is being killed.

Will fields' values inside ViewModel be preserved during save-restore scenario?


Edit: based on the answer to this question, I wrote this article: Android ViewModel Architecture Component is Dangerous

解决方案

According to ViewModelProvider documentation (check get method), ViewModel is not preserved when app's process is killed:

The created ViewModel is associated with the given scope and will be retained as long as the scope is alive (e.g. if it is an activity, until it is finished or process is killed)

In addition check Ian Lake answer to similar question: https://medium.com/@ianhlake/you-are-correct-the-viewmodel-is-destroyed-if-your-process-is-killed-by-android-ef611fcd51e6

You are correct: the ViewModel is destroyed if your process is killed by Android. Just like before, you should use onSaveInstanceState() to store any data you must have to later recreate your Activity in the same state as before.

I also recommend reading Android ViewModel Architecture Component is Dangerous.

这篇关于ViewModel是否可以在Activity中保存和恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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