Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 20  Data Binding and MVVM


However, this causes some architectural issues. To see why, look at it from an MVC perspective
(Figure 20.9).


Figure 20.9  Broken MVC


The guiding principle behind any architecture is the Single Responsibility Principle. It says that
each class you make should have exactly one responsibility. MVC gave you an idea of what those
responsibilities should be: The model represents how your app works, the controller decides how to
display your app, and the view displays it on the screen the way you want it to look.


Using data binding as shown in Figure 20.8 would break this division of responsibilities, because the
Sound model object would likely end up deciding how things are displayed. This would quickly make
your app a mess, as Sound.java would become littered with both kinds of code: code that represents
how your app works and code that decides how things are displayed.


Instead of muddying up the responsibility of Sound, you will introduce a new object called a view
model to use with data binding. This view model will take on the responsibility of deciding how things
are displayed (Figure 20.10).


Figure 20.10  Model-View-ViewModel


This architecture is called MVVM. Most of the work your controller classes once did at runtime to
format data for display will go in the view model. Wiring widgets up with that data will be handled
directly in the layout file using data binding to that view model. The controller (your activity or
fragment) will be in charge of things like initializing the binding and the view model and creating the
link between the two.

Free download pdf