Why do we separate ViewModels per Activity/Fragment? [closed]
Asked Answered
A

1

8

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.

Akan answered 14/5, 2020 at 7:21 Comment(0)
P
12

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.

Patio answered 14/5, 2020 at 8:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.