How do I effectively implement the MVVM design pattern for my android app which will also ease writing of test cases?

Ian Pinto picture Ian Pinto · Dec 19, 2015 · Viewed 19.9k times · Source

I am planning on implementing the MVVM architectural design pattern for my android app. I have read online that it will help me achieve efficient separation of concerns and easily write test cases for Data model, UI, etc. Need some insight/advice for this.

Answer

piotrek1543 picture piotrek1543 · Dec 19, 2015

Well, to learn how effectively use MVVM, begin with Android MVVM Design Pattern Examples

Here you would find that post:

I am the developer of Android-Binding. Like @Brentley said, it's a very new project but I do hope to get more buzz and experience so that it can be improved. Back to your question, I have written some simple introduction/tutorials on MVVM with android-binding:

Potential adopters please also register on the project discussion group.

Read whole topic. You would notice that MVVM is relatively new framework and it's highly recommended to work with it cooperatively with Google's pData Binding library and dependency injection library like Roboguice or Dagger2...

...but the best would be this one:

Approaching Android with MVVM. Building an MVVM architectured application using the Data Binding Library,

where an author is explaining using MVVM with Data Binding library by example - I mean by his own created app. He concludes:

It’s still too early to know if this approach is the correct way of developing an application, but this experiment has given me a chance to look at one of the possibilities for future projects. It’s something I definitely want to play around with more.

Model-View-ViewModel is interesting because in traditional Android architecture, the controller would push data to the view. You would find the view in your Activity, then set content on it.

With MVVM, your ViewModel alters some content and notifies the binding data framework about changed content. The framework do then automatically update any views, which are bound to that content.

The two components are only loosely coupled through that interface of data and commands.

Next aproach of using MVVM is really testable. From MVVM on Android: What You Need to Know

Because a ViewModel does not depend on the View anymore, you can test a ViewModel without a View even existing. With proper dependency injection for other dependencies, it is very straightforward to test.

For example, instead of binding a VM to a real view, one might create a VM in a test case, give it some data, then call actions on it, to make sure the data is transformed properly. (...) All of this can be done without having to interact with an actual View.

Read also: MVVM ON ANDROID USING THE DATA BINDING LIBRARY

Hope it help