11

I have a project with 1 main activity and 4 fragments all inheriting from the same "BaseFragment".

When first started I managed the whole project with the same ViewModel all through the main activity and fragments but after a while, the code inside became too extensive and decided to split it in multiple ViewModels according to the necessities of each fragment/activity.

I created one "MainViewModel" and used it in the main activity and the rest of the ViewModels inherit from it.

My question is if it is a good practice for reducing the code in the ViewModel? is it perhaps inefficient to have multiple view models? what other ways are preferred to simplify it?

Mycoola
  • 1,135
  • 1
  • 8
  • 29
Diego SM
  • 141
  • 1
  • 4

1 Answers1

14

Separation of concerns is almost never a bad thing. Ideally, each file/class should be responsible for one thing.

Additionally, you never know how the code will grow. Things tend to only get more complex over time, not usually simpler. So, while having multiple viewModels right now may feel like overkill, it will likely pay off later.

One case where a shared viewmodel between several fragments is ideal is when the fragments need to communicate with each other - they all would then use the activity viewmodel.

I would assume in this case you can use both approaches, though I have never done it, so I can't say for certain.

Bassinator
  • 1,682
  • 3
  • 23
  • 50
  • 1
    As a side note, I would be careful with the inheritance here. Are those inherited behaviors _really_ something that belongs in a superclass, or should they be in an interface instead? – Bassinator Aug 06 '18 at 17:14
  • Yes I know that sharing viewmodel between fragments its a good way to communicate, i have used before but in this case I'm using Bundle and args when creating the fragment to pass information from between them fragments to avoid having one big viewmodel and having multiple small ones and also as you said separating concerns – Diego SM Aug 06 '18 at 19:16
  • Reference regarding sharing viewmodel between fragments: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing – Aba Dec 19 '18 at 20:24