Android by example : MVVM +Data Binding -> Introduction (Part 1)

There’s nothing better that having clean modular interdependent code. Following design guidelines definitely does help achieve this. In Android, the MVP and MVVM patterns are very popular, they help having a good architecture in our projects. This article is an attempt by me to explain through a simple example the MVVM pattern along with Data binding. Why Data Binding? Because it enhances the MVVM pattern and makes it even better.

In this “tutorial”, we’ll build a Tic-Tac-Toe game.. Yes “we”, try following along, testing the code and trying out different approaches if possible, there’s no better way to learn than by actually getting your hands dirty in the process. let’s get started!

Note: You’ll find all the code for this project in the following Github repo.

An introcution

If you’re unfamiliar with the MVVM pattern or data binding, a brief introduction to these notions are given below. Feel free to skip ahead to the code if you’re already familiar with them (even though a quick refresh won’t hurt).

Model-View-View Model

Interactions between the MVVM pattern components

The MVVM design pattern is similar to the well known MVC pattern in that the M (Model) and V (View) are relatively the same. The only difference resides between the C (Controller) and the VM (View Model).

  • Model

Represents the Data + State + Business logic. It is not tied to the view nor to the controller, which makes it reusable in many contexts.

  • View

Binds to observable variables and actions exposed by the View Model. It is possible for multiple views to bind to a single View Model.

  • View Model

Responsible for wrapping the model and preparing observable data needed by the view. It also provides hooks for the view to pass events to the model. An important thing to keep in mind is that the View Model is not tied to the view.

Data Binding

Introduced in Google I/O 2015, the Data Binding library helps write declarative layouts and minimize the glue code necessary to bind application logic and layouts.

How is this done concretely? Well using data binding in a layout requires making changes to the layout file, it will have to start with a layout root tag followed by a data element and a view root element. The data elements describe data which is available for binding.

Show me the code !

Enough talk, let’s get our hands dirty!

Each component of the MVVM pattern is implemented in a separate article, I’m hoping this separation will make things clearer for you.

Thanks for reading this article. Be sure to like and recommend it if you found it helpful.

For more about Java and Android, follow me so that you’ll get notified when I write new posts, or connect with me here on Github and Linkedin.