Sometimes when I apply for a freelance assignment, I am asked “do you use MVC”? I’ve found it hard to answer that question. I know what it is, I don’t use it, but when I say so, I don’t get the assignment. I have explored the issue in a little detail more recently, and now I have the answer.
MVC doesn’t really fit the Android lifecycle model, as is explained in more detail here. Model, View and Controller are hard to match to Activities, Fragments, and other Android components. My apps generally have Activities and/or Fragments, and custom Views. These have access to an intermediate layer that manages data and API access, and everything that’s in the model and data layers. Using dependency injection makes it easy to fully separate the View layer, the model/data layer and the intermediate layer. This is not the case for and MVC model where there is a coupling between all layers.
If you don’t want to use MVC, you may have a look at MVP. (“P” for Presentation). Here it’s explained how MVP solves the issue of coupling between layers. It also explains how MVP creates one Presenter class that has all logic concerning the UI which is easy to unit test. To me, MVP still doesn’t provide a logical match between the model and the Android lifecycle, and to the way I build apps that are easy to test and easy to build.
So let’s welcome MVVM, described in more detail here. MVVM stands for Model, ViewModel, View (which seems more logical than “Model, View, ViewModel” because the Viewmodel really is in the middle). MVVM more or less matches the way I have built Android apps for years. It has a View layer, only handling UI related functions. It has a Model layer, containing the model, data, etc. Then it has a layer in the middle that connects the View and the Model layers. So far, I used “manager” or “handler” classes that access data and make it available to the View layer, that cache data to prevent unnecessary API or data access, and matches the structure of the data and API to the structure of the UI. MVVM provides a better structure to all this, and it is supported by an Android library. In the MVVP article they use RXJava and Dagger to make MVVM work. The article comes with an example in github.
I wanted to see it work for myself, so I created a little demo project using Dagger, RXJava and MVVM. I used to use Toothpick (before that, Roboguice, which is now obsolete) for dependency injection, but Dagger seems to be the standard now. I haven’t put in a database, when I do I’ll use ORMlite to handle it.