Android – When using MVVM on Android, should each Activity have one (and only one) ViewModel

androidmvvm

On MVVM pattern, the ViewModel contains business logic and notifies the View when it needs to be updated. It is also notified by the view about user events.

As I understood it, each Model should have an associated ViewModel. So, if we have the following models:

  • User
  • Account

We would have the following ViewModels:

  • UserViewModel
  • AccountViewModel

However, all examples I find about data binding with MVVM, use a single ViewModel for a layout. And recently, Google has introduced the ViewModel class within Architecture Components. This leads me to believe an Activity would have a single ViewModel that would connect to all related Models:

User / Account –> ActivityViewModel

This gets even more complicated if we think of a RecyclerView. Each adapter item could be a ViewModel itself, so an Activity with a RecyclerView would have multiple ViewModels within the list and plus a master one for the remaining view contents (assuming they require information from a ViewModel). For instance:

enter image description here

In this example, we have a list of Account ViewModels and one UserViewModel. How would this be embedded into a single ActivityViewModel?

Best Answer

You should have one ViewModel per View (Activity, Fragment or Custom View), with multiple LiveData, one for each logical unit. In the image one logical unit would be the user data, another logical unit would be the settings data, so you would have two LiveData exposed in the ViewModel.

View with multiple LiveData

These concepts can also be visible in the recommended app architecture google presented in the last Google I/O, where an Activity/Fragment has 1 ViewModel with multiple LiveData:

enter image description here