How complex should a ViewModel class be?

194 Views Asked by At

So far, I have two different ViewModel classes in my project: one that handles login and registration, and another one (HomeViewModel) that handles everything else. The HomeViewModel class is almost 500 lines long and has nearly 30 MutableLiveData objects. I already find the class quite confusing, and I wanted to ask if I should split it into different ViewModel classes. My idea was to either create a separate ViewModel class for each of my fragments or divide the ViewModel class in a way that similar methods are placed in the same ViewModel class, for example, putting everything related to chats and the messenger in one class. Is this a good idea?

2

There are 2 best solutions below

2
Annas Surdyanto On

I don't really understand how you present your project and what use case you are facing. Nevertheless, if you have one screen for both login and registration, I think that's fine. However, if you have them in two different screens, I think that's not the best one.

As stated in the docs.

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

I think you need to really change your perspective of how to use view model.

0
Sachin Singh On

ViewModel that big causes problem while writing test code. And also you'll face problem while finding bug, and refactoring the code later on, especially when the codebase will get bigger.

Main concern is the viewModel not following separation of concerns.

I think you might be using MVVM architecture right now, that's why you must be having so many mutableLiveData. You should think about moving into MVI architecture, it's an extension to MVVM architecture, but following separation of concerns much better than MVVM.