简体   繁体   English

我可以对一个片段使用两个viewmodel吗?

[英]Can I use two viewmodel for one fragment?

I am using MVVM in my Android project. 我在Android项目中使用MVVM。 I have Create and Edit fragments. 我有创建和编辑片段。 This 2 fragments have largely the same function. 这两个片段具有大致相同的功能。 If I write functions which they have the same function in a common view model, Can I use the common viewmodel with own viewmodel of fragments. 如果编写在公共视图模型中具有相同功能的函数,是否可以将公共视图模型与自己的片段视图模型一起使用。 For example Can I use like below; 例如我可以像下面这样使用吗?

 CommonViewModel(){

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

 CreateViewModel(){

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

  EditViewModel(){

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

Instead of this 代替这个

 CreateViewModel(){

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

  EditViewModel(){

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

Or can you suggest to me different way which I can use? 还是您可以建议我使用其他方式?

You can do this through Inheritance,Make a common view model and extend it in edit and creat view model, like 您可以通过继承来实现,创建一个通用的视图模型,并在编辑和创建视图模型中对其进行扩展,例如

class CreatEditViewModel{

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

} }

class CreateViewModel extends CreatEditViewModel{

} }

class EditViewModel extends CreatEditViewModel{

} }

You can not put these logic in BaseViewModel because BaseViewModel is extended by all ViewModel. 您不能将这些逻辑放在BaseViewModel中,因为所有ViewModel都扩展了BaseViewModel。

You can with the help of Inheritance, create a base class and put all the common functionality there, then create two more classes which inherit the base class. 您可以在继承的帮助下,创建一个基类,并在其中放置所有常用功能,然后再创建两个继承该基类的类。 this way you can achieve what you want. 这样您就可以实现您想要的。

eg 例如

class BaseViewModel{

    public void selectPriority(){

    }
    public void other(){

    }
}

class CreateViewModel extends BaseViewModel{

}

class EditViewModel extends BaseViewModel{

}

With the above example, CreateViewModel and EditViewModel both inherit BaseViewModel hence they have access to all the functions of BaseViewModel class. 在上面的示例中,CreateViewModel和EditViewModel都继承了BaseViewModel,因此它们可以访问BaseViewModel类的所有功能。 All the common methods will be available wit BaseViewModel. 所有通用方法都可以通过BaseViewModel获得。 The methods you would create in CreateViewModel and EditViewModel will not be visible to each other. 您将在CreateViewModel和EditViewModel中创建的方法将对彼此不可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM