chrrissoft
chrrissoft

Reputation: 189

multiple View Models for each screen

Hello devs I have one questions I hope you can help me.

I have read that Google recommends having a View Model for each screen, a screen could communicate with the View Model to perform many different actions. So the View Model would have many responsibilities, which is against the S of solid. Would it be good to have the necessary View Models for each screen so that each one has a single responsibility?

This multiple View Model approach I believe would improve reusability, encapsulation, and fragmentation; since if two screens need to do the same action, there is no need to duplicate the code of the corresponding View Models or pass the same use case to both. Each screen would access what you need.

Upvotes: 5

Views: 5420

Answers (1)

Yousef Kazemi
Yousef Kazemi

Reputation: 164

You have asked a great question.

These are just my opinion: You mentioned multiple ViewModels for one screen(let's say 'view') and the Single Responsibility Principle.

  1. Yes you can use multiple ViewModels for a view. But it is not typical in MVVM structure.
  2. The main purpose of ViewModel is to separate your concern and can test the logic of the app without launching the device or emulator(run at JVM level)
  3. SRP is not just the way you consider in ViewModels, Let me give you an example: Imagine you want to validate an email or phone, ... in your ViewModel. You can make a class for validation that follows SRP (It has single responsibility). Now you can use this class where you need it in ViewModels. Define your shared classes, repositories, or use cases that follow SRP and use them in your ViewModel. Not define multiple viewModels in your views. I believe that each view has its own ViewModel.

In android, viewModel also was designed to hold data for views. It means when your configuration changes your activity and fragment's data will not destroy.

Hope this helps you :)

Upvotes: 3

Related Questions