Android MVVM ViewModel and Repositories for each entity?

Alin picture Alin · Jun 13, 2018 · Viewed 7k times · Source

With the Android Architecture components and the MVVM pattern I have some question.

Based on most examples around the web there are usually simple examples.

  1. Have an entity for Room
   @Entity
   public class User{
   ...
   }
  1. Have a DAO
    @Dao
    public interface UserDao{
    ...
    }
  1. Have a repository
   public class UserRepository{
    }
  1. ViewModel
    public class UsersListViewModel extends AndroidViewModel{
    ....
    }

Now let's extend this and beside user have user_access and user_actions for instance, so have 3 tables.

Questions:

  1. For each table in Room I create entities. Should I have 3 Dao one for each entity (userDao, userAccessDao, userActionsDao) or just a general AppDao class?

  2. Same goes for Repository. One repository for the entire app or Repositories for each Entitiy (RepositoryUser, RepositoryUserAccess, RepositoryUserActions?

  3. If my app has one main activity and multiple fragments, should I create one ViewModel for each fragment?

Answer

Eury Pérez Beltré picture Eury Pérez Beltré · Jun 13, 2018

1

You should have contextual DAOs, let's say an UserDao which should contains the queries related to the users, if you have posts in your app, you should have a PostDao for everything related to posts.

2

Same logic for repositories, remember the Single Responsibility Principle for classes, sticking to that principle you should have repositories for each kind of entities separated (UserRepository, PostRepository...).

3

Following all the new concepts described as Jetpack you should have one viewmodel per fragment, unless for one strange reason you have two fragments that need the exact same logic, and that is very unlikely to happen since the objective of a fragment is to be reused.