Search code examples
androidviewmodel

Can I use two viewmodel for one fragment?


I am using MVVM in my Android project. 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?


Solution

  • 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.