programmer

Implement MVVM in Android

First of all, let’s take a look at the classic description of this pattern and analyze each of its components. So, Model-View-ViewModel (i.e. MVVM) is a client application architecture pattern that was proposed by John Gossman as an alternative to MVC and MVP patterns when using Data Binding technology. Its concept is to separate the data presentation logic from the business logic by placing it in a separate class for a clearer distinction.

Initially, in Android, this pattern needs a slight modification. More precisely, we need to reconsider the components themselves and their usual perception.

Consider, for example, Activity. It has a layout file (XML) and a Java class associated with it, in which we describe everything that relates to its operation. So the xml file is a View and the java class is a ViewModel? Seems like it, but kind of not. What if I say that our class is also a View? After all, a custom view also has an xml and a handler class, but it is considered as one? Moreover, both in activity and custom view you can do without xml file at all, while creating all necessary widgets from code. That’s how it turns out that in our architecture View == Activity (i.e. XML + Java-class).

But then what is ViewModel and, most importantly, where to place it? As we could see in one of the sections of the previous article, it is a completely separate object. And it is it that we passed to the xml file using binding.setViewModel(). It will contain the fields and methods we need to bind models to View.

Model is not different from its traditional understanding. The only thing that I would like to add from my own point of view – do not make calls to the database or API directly in ViewModel. Instead, it is better to create a Repository for each VM – then the code will be cleaner and less cumbersome.

Thus we get the following: the activity class “serves” only the logic that relates directly to the View, but in no way touches its behavior. Such cases could include installing a Toolbar or an add-in over TabLayout and Viewpager. It is important that only from View you can access widgets directly by id (binding.myView.doSomething()), because VM should not know absolutely nothing about View – communication between them is realized only through Binding. The logic of data loading and displaying is handled by ViewModel, while the algorithm of data retrieval is described in Model.