需要ViewModelFactory

ViewModelFactory need

我正在做一些 kotlin fundamentals and I don't really get in android with the ViewModel why sometimes there seems to be a need of creating it through a ViewModelFactory. Here you can see the codelab 的代码实验室,其中讨论了这个。

他们只是说要使用 factory method pattern 执行初始化,但我不明白为什么。为什么我们需要使用工厂模式?是因为我们需要将一些参数传递给 ViewModel 吗?或者是出于其他原因?每次我们需要创建一个ViewModelFactory只是为了给ViewModel传递参数吗?

我一直在寻找答案,试图确认是否只是为了传递额外的参数,还是因为任何其他原因,但我仍然不确定,我还没有找到答案。

在使用 ViewModelViewModelFactory

之前需要考虑一些事项
  1. ViewModelLifecycleAware Components
  2. ViewModel 生存 configuration 变化。
  3. ViewModelProvider' can only instantiate带有无参数构造函数的 ViewModel。

Why do we need to use factory pattern?

要用参数实例化 ViewModel 需要使用 ViewModelFactoryViewModelProviders 实用程序无法使用参数构造函数创建 ViewModel 的实例,因为它不知道在构造函数中传递的对象的方式和对象。

另外,你应该遵循依赖注入原则。 class 不应该创建它需要的依赖项。应该提供而不是创建。

例如 -

public class LogInViewModel extends ViewModel {
    private final LogInRepo repo;
    public LogInViewModel (LogInRepo repo) {
         /* this.repo = new LogInRepo(); Not recommended, It violates DI principle*/
         this.repo = repo;
    }
}