Search code examples
androiddesign-patternsdaoandroid-architecture-components

Why ViewModel's object shouldn't manipulate database directly?


I am learning Android Architecture Components.

For exemple, and be more easier to understand, If i want to build a TO DO LIST app, my item creation DAO should be

@Dao
public interface ItemDao {
    @Insert
    long insertItem(Item item);
}

and my viewModel could be use this DAO to insert an item in my TODO list. But, in architecture component, it is recommanded to NOT manipulate the database by the viewmodel but by the repository.

So, the code should be like that

public class ItemDataRepository {

    private final ItemDao itemDao;

    public ItemDataRepository(ItemDao itemDao) { this.itemDao = itemDao; }

    // --- CREATE ---

    public void createItem(Item item){ itemDao.insertItem(item); }

It seems redundant when we cannot understand why.

My question is : why?


Solution

  • I use the Repository for a couple of reasons:

    • Separation of concern I let the repo be responsible for downloading and storing all the data. That way the ViewModel doesn't have to know any specifics about where the data is coming from, e.g. if it's from an API or a cache. It also makes it easier to write Unit tests for the ViewModel, since all the database and API logic should already be tested in Unit tests for the Repository.

    • Reusability Lets say you fetch the data from an API and store in a database. If you put the code in the ViewModel and then want to perform the same actions from another place in the app, you need to copy paste the code. By having it in a Repository you can easily share the implementation.

    • Share data If you have multiple screens that show parts of the same data set, having one Repository passed around between the screens make it easy to share the data. No more trying to pass large amount of data in Bundle and Intent.

    • Lifecycle Let's say you download data from an API to show in your view. If you fetch the data in the ViewModel you will have to re-download it when the screen is closed and re-opened, since the ViewModel is discarded. However if you store it in the Repository it can use the Application lifecycle, so when you revisit the screen again, the data is already in the cache.