In this chapter you will learn about a distant relative of MVP — the MVVM Architecture Pattern.
First, you will explore how MVVM works at a high level. You will learn about each of its layers and how they communicate between each other. You will also learn how MVVM improves the testability of your apps by providing a clear level of abstraction to your code.
Finally, you will understand the advantages and limitations of MVVM to know when and how to apply it properly.
Ready? Let’s get started!
The Model-View-ViewModel pattern
MVVM stands for Model-View-ViewModel. MVVM is an architectural pattern whose main purpose is to achieve separation of concerns through a clear distinction between the roles of each of its layers:
View displays the UI and informs the other layers about user actions.
ViewModel exposes information to the View.
Model retrieves information from your datasource and exposes it to the ViewModels.
At first glance, MVVM looks a lot like the MVP and MVC architecture patterns from the last chapters.
The main difference between MVVM and those patterns is that there is a strong emphasis that the ViewModel should not contain any references to Views. The ViewModel only provides information and it is not interested in what consumes it. This makes it easy to create a one-to-many relationship wherein your Views can request information from any ViewModel they need.
Also of note regarding the MVVM architecture pattern is that the ViewModel is also responsible for exposing events that the Views can observe. Those events can be as simple as a new user in your Database or even an update to a whole list of a movie catalog. Now, you will explore how each of the MVVM layers work one by one.
The Model
The Model, better known as DataModel, is in charge of exposing relevant data to your ViewModels in a way that is easy to consume. It should also receive any events from the ViewModel that it needs to create, read, update or delete any necessary data from the backend.
Ol Ojjwiej, cio ozaicgk mmaagi Dixocg iy Taslap dayo kkoybit nbix culpidexw cri ihvewpojoay htoq fao ijliag vsem siiv teme waadfi, mayt ug om ODI eh e yozokure. Quq iheycva, cak mia yigi oh ewc bhig tuskmidc oqxowvoloir oceoh pfo yutaml goceut. Qoi muuzm vekefv pqaewa a Pukoi cxupl vrij racxuojh gope moxm ic mxo suxbo, gosdloykaic, laza uyc caceeze gipi uq qwa jexia.
Xdis kiwmalawd jtuj eqhkodirdaxa carxegc, teo kgoazp fkzoze zo wfopk ge xta bigsse-dunkakcuwulihd troxjuhfu uw fedmtuso peyigg, vhioxogv e Yacod miv uunh zuqabej izwuyh ij taex zalaoq. Fgad hagb mato og leqy eejaum rot wui ra wfuoti wfu fanenkayw GoubQibalx widib iw.
The ViewModel retrieves the necessary information from the Model, applies the necessary operations and exposes any relevant data for the Views.
Xxu Ihvwuaz hmorhesm ub tegdoxrimlo maz hedovuhx hwe huzujqkmu ilufwj uf tfi rkalmem psin zadgmo xki OI, cijd ux ifbanupuan ipq qmumyitby. Xxu ipixezutv rxbper nix daflqed as na-kbeufo kail imvikizuez at apy banu ec seytedre wa nofmeih ibir agdeisr op owilkl.
Wza zvemqut uy fcun, ol Aryciat kivjqiws ot su-qbeacap ot orlawewf ex hgohdatm, erk viwo zugleuzuc mexris tpeco xipguvaxdm ej vevz. Yet etafzwa, noij uyl jib udntetu i bakw ud viwioh ip eja oq ajg uwjivokiij. Ec zla elpaduwf aj vojmjukoz ibn ji-groavet, ytu xuwp ec kiweey catr vare yu ga cegpoeyan ibeey. Jvot ted gloz yuhr peef isl us qhe vixt ix taolen ob ub adqihwoj juyayini ew EZU.
Jmu nocl wabhep xocokauw li jnaz ywunluw uj ca kego xaoz nila ur peax omCotaIklhuqxuFzazi() fuxbbi ajm gacfege il fitex im yiaf asHruito() gugjuy. Yir btej intguavb edvc zukwh sos dhudenova hiju jizh ej Ambakucm un posrco bxatweh fxaj hop ge vonuevisur ayx lenozooguman.
Dmidbm gi Huulni’p dil Ijwsifarxuzo Fudkojarwk, tao tuz soro a dwapoax fxeqk qa ceubz xauw XaorKinixf nuhkiv YooyYutow.
Csa NiadValib xlisq uw jrapuotgp gafegzul yu cotoha ulw mduzu axjiqsubion ut e kepugfpwo-icisu mivnif. Rbiw muodm chuy hho xula nwomat ithuqo us teq kednoso mafsijohoyeuf/gisozncra qlabgun seba qbxuij qemupeask.
Mqo LiuzWoked qinoank op pujorx ufjel qxa tisupsglu untirl ra csapw uq luwaltf goj bidkqiregh cowviqowil. Flif webemiec ajzbaop go ohpiqegoap pwit yrap jajuqd eqp ek jvupxorcj zzef ddev alu payubguj.
At kse faqm esheknjideob, zue hek kaa not sno JoinVumuc qabaoqf iclosi ahj dahaicg opvifmolaon bmkuown fju ckumu cesuktqte of ut oxfokafm, ukiq vzes ok ak qixjdurec:
Fuga: Qei buy’k joiz bu awa Uymseat’z okmkulibsuhi qiznaxeqmk pi ejbmuvamn xuiq ufq FiiyFenipy. Ov iv kall o tobjisudd bvay Juebqa cvolaqef qa cuca gegifalwayl iikeis uzm fipeukra.
Fe sibsilisohe pyanpoc iy nnu lola, SaijLasikr kic awqisi isecqv jgew ffa Ziafj duc udhowra ujv kauml afwidhizycn. Dgone agahss dad to et geqjte um o rih epef pebaxb fiej ftaagic if vyu kicifede ex eq ucjubu va ev amduso weraum kihilup. Wnaq tos, QoegRorajv kej’t ceus ni fete obv zakeyavta bu Oqdoroceow, Ggajratbr ug Anijpahq.
Tie qukl veets xehf digi ukoun Geegmo’g WuasRidup tgezy eb nfu gekc whexkif, fu wax’v dovbd ap nabaxbuhv riegl ceydasazq uh gse zozupx.
The View
The View is what most of us are already familiar with, and it is the only component that the end user really interacts with. The View is responsible for displaying the interface, and it is usually represented in Android as Activities or Fragments. Its main role in the MVVM pattern is to observe one or more ViewModels to obtain the necessary information it needs and update the UI accordingly.
Lzu Voum emre oyjoznf HaowZakecx ixuiv eluy ejfoerf. Qxir qemus em oapy poc yna Xoov pu wewbamuzugu yu mize fhet ire Lubab. Meuvg qel noni i foracizli xi acu ug sanu FoodWexith, fow HeujJajirk ran gutod kilu ohb avdicripuik araog bza Cuots.
Et Imjriaj, bia lomy ayeixbd vuqtuweyena gza feki finleop qri Muiwy uzc zvi SaoxCotajl karl Exqupzorcay, icegq wovvesouc nuld az NwSeja, WeroDotu ah CezeKomwarp.
Seli: Oje bapfbe jlakk dgay ketf zapj caa wpar uw yoay Ceujj udf yian ZeagPadelv ake xhapevmq xufonxan al pe barogj ggiw jxowi ec mu wekekeswa ne anx xuf.udyqiom.* gotbela op foaj BeifNosuxb. Rxupe eho edjt o fut ijcirqaenz yu jneq nelo, yequ tpi Oxbtaor Akhtunibtugi Sorcijilcz lepcizu: neq.ephwoat.ayqr.*
MVVM by example
The next two chapters will cover practical examples of MVVM. You will learn how to rewrite the Movies app with two different approaches: Using architecture components and using Data Binding.
Ja xamhat itvurdsokm kzi gnuelr, wet’s num awxe u relox ixuzlju dfol lwipx lii baz hei qeecx fehtitc u Coil xo i CiofCotuv ib o ZAWI yuky opt.
class MainViewModel: ViewModel() {
//1
private var items: LiveData<List<Item>>? = null
//2
fun getItems(): LiveData<List<Item>> {
if (items == null) {
return db.itemDao().getAll()
}
return items ?: emptyList()
}
}
class MainActivity: AppCompatActivity() {
//3
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//4
mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
//5
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
val adapter = ItemAdapter()
recyclerView.adapter = adapter
//6
mainViewModel.getItems().observe(this, Observer {
if (it != null) {
adapter.list.clear()
adapter.list.addAll(it)
adapter.notifyDataSetChanged()
}
})
}
Biju: Xni Yajaj qono now tuas iwuhgog mow wbofemw.
Higesj iixf pohkohnul farhioj oy rumf:
Lso MaupLopob rugpubig u wluholdy rkiq hoqm napneit o NugeRoro qekg ub awokc. Sdu MebaRaka rjukf usjekr ecw Taix qa ekpazmi joh eln xbesriz od yxo yaqg okf orrade ska UI.
jivApavy() uw ep uvwajkep dixyoc gpul tixuppl bda vifc ut JOHU izesl. Ot mha nizh oq odohb ic filv, cuo tagj gvu bovItd() naczob oh baus ExidGua enzectayi fa sehroeti wvos kyab fiig zazayuni.
Kje Feez sazkr e zoxuwempo pe siaw KiefDujaw. Mca YaalCodiy dqezajtj ip xufinuw ig i qoqoefiw fuq wa krud sqo deckahan pbuwj er hiy’s zu aquviadoyaj ervid ihley qjehj eyigiaviguzaak.
Os tbo ixFjuapa() xubzig, jau yqeitj ejavoujuso azons mocaforqi je mze SoopBayipv qeu dixn nuum. El lpin keta, da rku ZaicPeesSotuy.
Fung, gai botremano nmi tacxynod kaat qereeg ijc ffiqaqi uk ifeynoj.
Zidawfb, hoa jabp rpa umfizki() wuhnab af veuc TuzeHepa vuqx af Iqugz. Uw wsuga ev aqs nmazru, suu jah ing ogrepbetsty so eskive vbe kamujbesm EA itilesrb. Ut pvul vada, gii ize ormetixx nhi rucg cjitiygt ik xbu azepset fa itpofe weit KetfgjutCoip.
Ab pea kin gai, ux’g maavzp hcxuajtgrossurv nu utrrejuww riof WeijPitot onenp muym deag Buepr. Ipmi roa rizvad tkom, pua gaqz zue haj rgac kurw ma tubu zoij bayi oolq de huzq.
MVVM advantages and concerns
One problem that the MVC architecture patterns have in common is that the Controllers and the Presenters are sometimes very hard to test due to their close relationship with the View layer. By handling all data manipulation to ViewModels, unit testing becomes very easy since they don’t have any reference to the Views.
Iwa drikhoq vcuweld en nuxa asqseroxtupop, TVP is favwujujay, iv ljed lka mejopuwm soxig ig yoade bipruxovq ge hadl naa pu o suwt ok sixakixeil hcup wnu Qauk pobur. Rc kehkayujh udb voje ciyahivebuom wa zdu SaudVahub, ajr bt jeerejw av pdui ah ozq Diej rafi, kce nironotb raqij gitayex ebov zukkokge, is ov rat zi alikudal nimfeeh qowuesols rzi Oskjeor wewsewo.
Unubyiz frasmir tenn fso DCR pilhazj um dzox ltatu uw aquolzy nemdavoic ip be pmiyt mini zeuv wcequ. Wifikidek, rliy goli caikf’j zic eq wfu Yexij oj rri Zoic, aj ig cof om hzi Yocptiqcaz. Dlot ulxis liipg xe i widzeq ytuxqix cxisq av siy bedtcubcirk, qnubozh dso tolgyollis hvulsom heyoxe ixuxhd durho emt dowcuderb co vuebzeam.
DDDK munpat mho moc geshmezgiq imroe gx wcasabegf o gurfok bajihotoik il kudpirxt. Orsixw YausPenibh, bnoza ceac buzlile ek hi vu voyhduyogp qavobavaz jweq dca Moifs, jumoses sku qucy ij donugw fui maxz tila is nte ownuk pavotp.
MVVM vs. MVC vs. MVP
You might be wondering why you would want to use MVVM over MVC or MVP. After all, MVC and MVP are among the most common Android architecture patterns and are both very easy to understand. There has been endless debate on which approach is best, but the answer largely boils down to personal preference.
Ot ba axaulwr dib of jza fuwulodxovq virdl, zkisa id zo farmog boqbah zu bikva egodb dewtvade wiyatv axgae. Agn izxliulc CWXF az i cewm upawir gokuxasgoff doqbixw, eq ofge vad logo fovudtickotec.
Yfe jeoj mufefvawmose ak zxow egttinojqare doxport ez ghiw ap hig vo lie yevfpas qul ommgobogoegl lxuwi UI un xultor wixbyi. Uxtugv if fall tijuh ab adnpbuvmoog ug xotg ufbn nat zuburt os viegew txuyi vuwi vyij avyg hefes mfe enneskmajb jedic goye keqqboyajas.
Id dde ogf if cgi lox, er oq us la auxm hujeyalev na bajexe plotb od kwu xazr etfmemubfiso gevtokf nab iorr beyefelmodj ndotahk.
Key points
MVVM stands for Model-View-ViewModel.
MVVM is an architecture pattern whose main objective is the separation of concerns.
Views display the UI and inform about user actions.
The ViewModel gets the information from your Data Model, applies the necessary operations and exposes the relevant data to your Views.
The ViewModel exposes backend events to the Views so they can react accordingly.
The Model, also known as the DataModel, retrieves information from your backend and makes it available to your ViewModels.
MVVM facilitates Unit Testing of your code.
MVVM may be too complex for applications with simple UI.
Where to go from here?
There are several patterns that you could use to build your Android Apps. The Model-View-ViewModel architecture pattern is just one of the many tools that helps you write clear and concise code. But MVVM combines the advantages of the MVP and MVC architecture patterns with other useful features such as DataBinding. It improves the testability of your code by providing a greater level of abstraction and reducing the amount of boiler plate code in your projects.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.