我可以为一个片段使用两个视图模型吗?

Can I use two viewmodel for one fragment?

我在我的 Android 项目中使用 MVVM。我有创建和编辑片段。这 2 个片段具有大致相同的功能。如果我在公共视图模型中编写具有相同功能的函数,我可以将公共视图模型与自己的片段视图模型一起使用吗?例如,我可以像下面这样使用吗?

 CommonViewModel(){

  void selectPriority()
      .
      .
      .
   otherthings...}

 CreateViewModel(){

  LiveData<CommonViewModel> cvm;
      .
      .
      .
   otherthings...}

  EditViewModel(){

    LiveData<CommonViewModel> cvm;
        .
       .
       .
     otherthings...}

而不是这个

 CreateViewModel(){

  void selectPriority()
      .
      .
      .
   otherthings...}

  EditViewModel(){

    void selectPriority()
        .
       .
       .
     otherthings...}

或者你能建议我使用不同的方式吗?

您可以在继承的帮助下,创建一个基础 class 并将所有常用功能放在那里,然后再创建两个继承基础 class 的 class。这样你就可以实现你想要的。

例如

class BaseViewModel{

    public void selectPriority(){

    }
    public void other(){

    }
}

class CreateViewModel extends BaseViewModel{

}

class EditViewModel extends BaseViewModel{

}

在上面的例子中,CreateViewModel和EditViewModel都继承了BaseViewModel,因此它们可以访问BaseViewModel的所有功能class。所有常用方法都可以通过 BaseViewModel 使用。您将在 CreateViewModel 和 EditViewModel 中创建的方法彼此不可见。

你可以通过继承来做到这一点,制作一个通用的视图模型并在编辑和创建视图模型中扩展它,比如

class CreatEditViewModel{

public void selectPriority(){
  //to something....
}
public void other(){
  //to something....
}

}

class CreateViewModel extends CreatEditViewModel{

}

class EditViewModel extends CreatEditViewModel{

}

您不能将这些逻辑放在 BaseViewModel 中,因为 BaseViewModel 由所有 ViewModel 扩展。