android 的 ViewModel 的奇怪行为

Strange behavior of android's ViewModel

每次我离开 activity 和 return 时,当我尝试通过在开发者选项中启用 "Don't keep activities" 来模拟应用程序的配置更改时,会重新创建 ViewModelViewModels 不应该处理这些情况吗?

我可以通过将 activity 的状态保存在 onSaveInstanceState 中来解决这个问题,但是使用 ViewModel 有什么意义呢?

When I try to simulate configuration change in my app by enabling "Don't keep activities" in developer options every time I leave an activity and return, the ViewModel is recreated!

AFAIK,"don't keep activities" 当您离开它们时会破坏活动。它不模拟配置更改。

在 Android 8.1 上,设置明确指出:"Destroy every activity as soon as the user leaves it".

Aren't ViewModels supposed to handle these situations?

ViewModel 系统处理配置更改。它不处理被销毁的活动或被终止的进程。

要模拟配置更改,请更改配置。例如,您可以旋转屏幕或更改区域设置。

I can handle this problem by saving my activity's state in onSaveInstanceState

任何可以进入保存的实例状态 Bundle 的东西都应该进入保存的实例状态 Bundle,因为它处理配置更改和进程终止。

what's the point of using a ViewModel?

ViewModel 用于无法进入已保存实例状态 Bundle 的事物,例如:

  • 大东西(Bitmap 一张照片)
  • 活物(LiveData、RxJava Observable 等)
  • 输入错误的东西(你不能把 Socket 放在 Bundle 中)
  • 不属于 "instance state" 并且在 Android 终止进程的情况下不需要的东西,但您希望将它们放在身边进行简单的配置更改
  • 等等