【问题标题】:Can I use two viewmodel for one fragment?我可以为一个片段使用两个视图模型吗?
【发布时间】:2019-08-14 10:31:59
【问题描述】:

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

 CommonViewModel(){

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

 CreateViewModel(){

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

  EditViewModel(){

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

不是这个

 CreateViewModel(){

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

  EditViewModel(){

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

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

【问题讨论】:

    标签: android viewmodel


    【解决方案1】:

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

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

    }

    class CreateViewModel extends CreatEditViewModel{
    

    }

    class EditViewModel extends CreatEditViewModel{
    

    }

    你不能把这些逻辑放在 BaseViewModel 中,因为 BaseViewModel 是由所有 ViewModel 扩展的。

    【讨论】:

    • 是的,我想,这种方法更好。
    【解决方案2】:

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

    例如

    class BaseViewModel{
    
        public void selectPriority(){
    
        }
        public void other(){
    
        }
    }
    
    class CreateViewModel extends BaseViewModel{
    
    }
    
    class EditViewModel extends BaseViewModel{
    
    }
    

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

    【讨论】:

    • 我已经在使用 BaseViewModel 但即便如此这种方法对我也有帮助。我创建了 CreateEditBaseViewModel 类,并编写了它们在 common BaseViewModel 中使用的所有函数。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2016-11-23
    相关资源
    最近更新 更多