Why do we separate ViewModels per Activity/Fragment?

Viewed 1373

I've recently started working on Android architecture components. I found MVVM architecture to be extremely handy, and I would like to master it. When designing my apps, should I be using multiple ViewModels for different activities/fragments or should I be using a single ViewModel for all activities/fragments? What are the pros and cons of these two approaches? Thank you.

1 Answers

It depends on the state that you need to hold. If your fragments are isolated from each other, then feel free to use a ViewModel per Fragment. If you need to share the state (and by state I mean LiveData), then it's reasonable to have a ViewModel per activity. But generally, the smaller the classes are, the better.

So I recommend having a ViewModel per fragment except for the case when you need a shared LiveData.

Related