ViewModel 如何在配置更改时持久化

How ViewModel is persisted on configuration change

查看 ViewModel 文档,它说:

In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel.

如果引用它的 activity 被销毁,ViewModel 如何不被销毁?一旦我们创建了一个新的activity,它是如何重新连接的?

在幕后使用 retained fragment。保留的片段在 Activity 重新创建(例如从配置更改)中保留其状态。

参见 "Architecture Components Introduction" 来自 Google IO 2017 的演讲,其中 Yigit Boyar 谈到 ViewModel

答案是,如果您使用 ViewModelProviders.of(this).get(YourViewModel.class) 创建 ViewModel,该库将为您缓存 ViewModel。如果您使用 "new YourViewModel()" 创建 ViewModel,则每次 activity 配置更改时都会重新创建 ViewModel。 在 ViewModelProviders 中,它将创建一个 HolderFragment 以添加到您的 activity 或您的片段,它是不可见的,当配置更改时,activity 被销毁,但缓存仍然存在,所以下次 activity 创建,ViewModel 将重新连接到它。