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.