ViewModel中的LiveData对象为什么要在声明的时候实例化?

Why should LiveData objects in ViewModel be instantiated during declaration?

请参考 Google's Architecture Components 教程中的以下代码:

class MyViewModel extends ViewModel {
    private final PostalCodeRepository repository;
    private final MutableLiveData<String> addressInput = new MutableLiveData();
    public final LiveData<String> postalCode =
            Transformations.switchMap(addressInput, (address) -> {
                return repository.getPostCode(address);
             });

  public MyViewModel(PostalCodeRepository repository) {
      this.repository = repository
  }

  private void setInput(String address) {
      addressInput.setValue(address);
  }
}

请注意 LiveData 对象在声明期间实例化。

据我所知 this answer,在声明期间或在 constrictor 内部实例化它们之间的区别很小。然而,据我所知,当 LiveData 对象通过构造函数实例化时,可能存在 NPE 或过时的引用,因此 Google 的建议是在声明期间实例化它们。

我的 hunch 是它可能与通过反射创建 ViewModel 对象有关,但是我一直无法找到它究竟如何影响创建那些对象。

为什么 LiveData 对象要在声明时实例化?

Please consider the following code from Google's Architecture Components tutorial:

那不是教程。它是一些代码片段的参考,其中许多不会编译,因为它们用于说明语法和调用结构,而不是实际 运行。

Please note that LiveData objects are instantiated during declaration.

这就是编写该代码片段的人选择做的事情。

so Googles' recommendation is to instantiate them during declaration.

Google 没有这样的建议。您引用的代码片段是一个 示例 ,仅此而已。

Why should LiveData objects be instantiated during declaration?

它们没有带有初始值设定项的字段。如果您愿意,欢迎您在构造函数中实例化它们。 ViewModel 有关于构造函数的特定规则(例如,如果您不提供工厂,它需要有一个零参数构造函数,或者 AndroidViewModel 的一个 Application 参数构造函数) .但是,除此之外,你可以做任何你想做的事情。

使用初始化器通常更简洁——其中初始化器是一个可用选项——因此可能倾向于使用初始化器。