ViewModel 状态如何自动更新

How ViewModel state is automatically updated

在 activity 中,我声明了一个计时器

Chronometer chronometer = findViewById(R.id.timer);

ChronometerViewModel viewModel = ViewModelProviders.of(this).get(ChronometerViewModel.class);
if (viewModel.getStartTime() == null) {
   long startTime = SystemClock.elapsedRealtime();
        viewModel.setStartTime(startTime);
        chronometer.setBase(startTime);
    } else {
        chronometer.setBase(viewModel.getStartTime());
    }
 chronometer.start();

视图模型class

public class ChronometerViewModel extends ViewModel {
  @Nullable
  private Long mStartTime;

  @Nullable
  public Long getStartTime() {
    return mStartTime;
  }

  public void setStartTime(final long startTime) {
    this.mStartTime = startTime;
  }
}

当我旋转屏幕时,chronometer 会自动从之前的状态恢复。但是我没有编写任何代码来在配置更改时将计时器的当前状态存储到 ViewModel class。状态是如何自动恢复的?

我正在关注这个 google 的代码实验室 tutorial

编辑:我对 Chronometer 的 setBase 方法感到困惑。我假设我的状态变量 mStartTime 会自动更新为 Chronometer 小部件中显示的当前时间。现在我已经检查了 setBase 方法的文档。由于 mStartTime 在配置更改时持续存在,我们可以使用 Chronometer 启动时的旧值。所以 Chronometer 实际上恢复了。

您的 ChronometerViewModel(作为 ViewModel 的子项)不会随着 Activity 的方向变化而被破坏。

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

A ViewModel is always created in association with a scope (an fragment or an activity) and will be retained as long as the scope is alive. E.g. if it is an Activity, until it is finished.

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.

我建议你阅读 ViewModel 的文档:https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html

ViewModel 生命周期 如下,Android 出于同样的目的引入它,以便它可以在配置更改后继续存在并且直到 [=22] 才丢失状态=] 完成

顺便说一句,您是否因为这种行为而遇到任何问题?