Does SharedViewModel violate Single Responsibility Principle?

Viewed 147

I have one activity and 4 fragment, I have SharedViewModel which helps me to pass data from Activity to all other Fragments

                             Activity
                                |
                          SharedViewModel
                                |
         ----------------------------------------------------
         |               |                |                 |
      (Fragment A)   (Fragment B)     (Fragment C)    (Fragment D)

Now here you can see that SharedViewModel has Activity along with all Fragment's data. So, one SharedViewModel contain variables and functions of 5 different class, like variables such as LiveData, other database related functions or some network operation related functions.

1) only one function is used as a common to share data between all classes.

2) Other functions are individual functions of all other class.

so is this violate Single Responsibility Principle? If not then how?

1 Answers

Single Responsibility Principle for MVVM can be referred for repository pattern from where you expose your data to UI using ViewModel.

So imagine that ViewModel is only responsible for each request of data from UI to Repository and provide response back from Repository to UI back.

On the other hand, Repository is only concerned with providing data back while eventually it doesn't matter whether it comes from local db or from API call.

So, that's how Single Responsibility can be derived for MVVM.


Now, for your architecture, it is 100% okay as soon as your SharedViewModel just provides data updates to each UI (Activity/Fragment) which can be considered as common across all via LiveData that every component commonly shares & observes.

If you place a data holder (LiveData)/variable that can be considered as dependent for only one UI then you should use individual ViewModel for that UI,

so about second point, "Other functions are individual functions of all other class." I would suggest you to create ViewModels related to your UI seperately & make ShareViewModel simple & tiny as possible so that you don't expose your one UI operations to others.

Related