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.
TicTacToe-MVVM - Sample android application used to learn the Model View View Model pattern and DataBinding in Androidgithub.com
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).
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).
Represents the Data + State + Business logic. It is not tied to the view nor to the controller, which makes it reusable in many contexts.
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.
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.