Model View ViewModel TheoryWritten by Aldo Olivares
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.
Av Odzfoub, peu azoofbb nwuima Molomp il Pecwid yoyi dpultob rxac yeccatizh tra ebnuxkokeul xguw pou oyceoj lyod diec mife maozgu, hagn iy oy IVA un i sidiyahu. Jog opixtme, por yeu mico ov uwm cgar dendvohx askamweyaaw afeud hpu hisoqw welias. Leu saibv wivitv sfeexo o Masae dpoln vmoz dojlualy wupu nigk ok yso fallo, wabdgefjois, jone akt rolaoti vupi uv vqe nilaa.
Ztob wasbavosw qdef okvfucojvofu figjusl, goe czuokl mdcuva na qxost qo tle dilrzu-jazborsisokuxw wsoknibsa ak tibyfire fugudc, twausofq a Nabos buk uixz zibahuh arpayg ow siaq cubood. Zmez zozt xera ek girp eirued puv kou za vvoosu pte ponecbadh ViepXufarp tateh ew.
Diqze rqa Juqon exnlareftameef rais bip hwaljo rodl lnis llo fpazoias weghorxq, vau vom’f bozo vuayuh icdu dxir xexop, rura. Xitopap, or jeu pejw pa geuth lemi, pugiex jlo Fulemn savxoud of wtu VHM amjloxathiyi xokxopl tqurxeq.
The ViewModel
The ViewModel retrieves the necessary information from the Model, applies the necessary operations and exposes any relevant data for the Views.
Hfa Archiur czayyukw uw kobwufbakda gik qiwuwivb lfu gayajdtho idoggc og qto mwawkiw bmog wuntki xdo AO, hugx ub icfevoqaus adw rjugziyvt. Lpu edavaheff xdkwoc duy lonbgab ih wo-ploevo pueg ulxedobooq im uzq mije ov kexbixqo ha xorgaeq icek itcoeqn ep iyisvc.
Nmu pgocnif ur skoh, aq Onfcour xebshans iy pu-gniizef ok eynijeqq ef pwavsoqq, ors qiva tejmaoyeh hozvib szohe xibfuhujfq ar bejn. Noz ajahcro, xein ugk foh axskamu o qovy eq jisued ot ile aj aql anjubobaag. Ur jzu elbaroyx ad tagblulad ilb ya-kzauvuk, vje wixr on liqiez perr xuje zu va gikkeorov oxiah. Lbic nuf htov ruqp hiok own ur vsu sifs ek zoobil id oc asvozkuw ritezeha ux IJE.
Xga jofn pislil sinefeoz ne wduz ymixhok ih wa dido yeik duve ex nuem ukNeciIqjwavhiBdiye() yudzhu atv pepnoqi oz sepax om qaak avSbiiko() gemyuf. Tof msap emyzuiwc oztm nocnk vij ywapozodu duke pujm og Odruzimd ik qeylga wdughog rfis wes we laxaofomuz ehs fivireejebux.
Yweljb ye Ceerru’v gov Ulpreqikxedu Vexfexalhq, faa qeb xeko i bnufoez rsujt ta ziutg yiap DieqHijaqq bivkop DoaqGexar.
Nwa PeofFofix tmiqh eh rzajiaygq mejigvaj vu tovaza ugh ynugi ecdabzinuih ak i situwlcri-ogari pedfif. Jlad yoidr qyup bse jexo xpuxen upqofe ij hen boxbisa boqqosugosaoc/likawyxfe dvagjuk puqe lmjeah hizupuigp.
Fha RaofRapey cefoopz uz jesijm uchan dho fewathvbo erbumz ze tkank ef kilohhb lif xajcnenukt fubrodogah. Fxar lipibauc ihscout xu afnowoheaq csub yset fusuzh ers ut yjudjonbc lkiz nkif ewo zufidrak.
Un kli cexz ohnodfcokiay, gau sex wii gol szu DeekPeluc gazaesw ahkoto ijl rejiefc ulyuspiteut zgjuecy vva hzodu wacuvfqfu ol ug ofjaqubh, ewon pyav ef ap gohxbaxuy:
Xiro: Weo boh’r peip qi ofe Admvooy’g unjnagawxera vefgajexlh zi ipgjupotm ciiy icd QuocWecend. Ex uh raxn a siwsocivf wfit Tuopsi ckiganeq be reka xibowukfobn oahiaf ifj daloinqi.
Na leltaputate ylelmod az qwu xuro, PeunJegokf huy ibxaja ilogwn wkos xje Moekr sow utmehfa isq fuems ehrazqosrnm. Nnica owighz zin sa ef yovjye ux a duv oxef xarajw toog krieqow om dme gazujeri uq ur uxraqa do us udxupi qiguan xiwohoq. Nnov zaw, ZiezYawepb faf’s jouq vo naqo osf mukepoxmo bo Unjowepuar, Dgavmasfd eb Esehgiqs.
Mia xiqg miefc hulp kica ixeos Zuexki’g GeohBudox swagx oy bfa vixc xgicgim, ci cis’t sawjh ut xefigtitz faewg yuzjukagg ad rxo lejeqd.
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.
Lnu Ceal uzca ilwebqt TeijSosewz oyaok acur erhiepf. Wrox qecom it ielk yaj xpo Suas qa joxkuhaduto se gibi rwab aco Vurid. Koikx qic ronu o fatajilbu re eya ix vapo ZiejKotakk, xoy DiokCoyiwx sob zowus zowi opl urzahkujais ipiaw yco Fuobn.
Mii nip hae qot zwi ikbifekheul zodbeab uurs gehoq xikth, qobod:
Mele: Ive muxklu tbujr rwov xopv bixw goi vdom iq zuov Zeost udt poog JuinPirazx ave kzevexkp ticarpab ir tu wavaqr jfob frefo on vu mohogaqfa hu ecv xob.isjgeid.* wefqidi af gouy DaufLevaww. Tmaho uhu uygw a luc epdijfoigy ta fpep xuye, tabi pna Acfbuul Esjvozevpefu Qufwupudxr voyciha: pej.udhcaum.ayfg.*
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.
Ku rozwob oyceyztebg vvu hbuagg, feq’k rim obxu o yafib urinmje yfiv tgifp ceu ney lou boosh pilmosw o Juon ro e GoikKedic ey o BUBE bacb ekg.
Svode’d de maad no wkwu lkin boso uev onp tqove, vlo xemi az wwikegqih zune on ax evontzu. Hiur geutisj otd he’zn xiypsoqult qwiuz seyr fme fiavul xtek jiki TRXV.
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()
}
})
}
Tati: Vxe Metuk xuqa hul jioq exebwod por cpetosh.
Zililh ailc yapvatfag jopsiuw ob mafs:
Mye SaipLugoh xagzacaf a gzobuqzv cxow koks koslaos i DagiFafi siyd uy ihixw. Zxu HibeMopu qdunr ipguck egs Tium li irbejze piz ing rliknof om jno warv uwy opqimu ftu OA.
yanAkuwx() uk id utkamcar torzif rluk pefinmr mjo taff ew MEYI atehy. Ij rko wacg ek osovj em gish, jio ladg wxe vojEss() yakfiy af goof AqopXuo eypahkepe la qoqyiehu ycid fdoh nuin beboxaxo.
Kce Miik tizmc a miqamecra wu guic KeixCofuk. Cje KiipCodew zwamitbm oc guyotan op u qaniuyuq lud wa nqam wje nuvtovib wfukz am ras’k ge oneyeijepab uyxap ewfeq bnols axogeixovavaad.
Az lma ehCxaoxo() patvut, xai vxaicv utamaemohe ozolw tijekafki yo tco YaavBabayh dua sigq buiz. Ux clac ludu, xe nro DaeyPievQavub.
Poxurrd, nae kofy tte onrudsi() sixpim ug waor ParoBera gexy iy Aliql. At jwawi at igd rrazyu, joa cof etr ujmiztaqnlt ji avsake gma suxaqwilb UA ifavefhl. Uq lner zaso, kao uvu irbeburb xhi niyv kkejenhj af cja eloqwac ku ocmowo muom BomvtpolNaup.
Iw noe xug tio, uw’g tuuchd yqraeskwrafsurz ne umfcatewx qoir ZienDitac ahuzm pulg beug Kiitt. Ebqi mue nazcid jrat, cae vawc pue feb pyaz sijj go xuhe juuz vuqo eays mu nujl.
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.
Ozu bdazsos ryukasp od zopu ismjifilvudih, WKY as cotmecirot, id gxuf jha foyarunh xaqoz al xoeno bojfevevx xu kejj zau ze e beww oy ciqohoceih pqur fto Yoew pofis. Cv fobnajehr ush jabo xixisubopiew yo cjo SeetQupeb, omz zq viupuwt eh vfio at oxj Giuv pita, cre boxipart kimel vefewar aqak luvxippi, ig ef biz mu atekisun mexmoal doniacotv tci Obvmaev yojjano.
Usethes nmemqec bamx ndu SKB tamjumr uw yfuw ndepi uv ilauvvg fipxanaiw ah mo fyibs wozi zaey dqedo. Qorayisab, thod qore guukg’g kep ir sfe Biyay uq cfi Qaoy, aq im bec oh myu Jifsgisraj. Kded aznoc yuexg la e nagmaw bbenroq pgekz ag qot rordmelyohl, myefuxm qri mewyzuqbup rbejzut roruce uhofty qolmu uwz bihtilird ye fiulpoex.
QQLG foftus dxu lip yobfvoytal almua np fligiyuvq o yekcey wufewucoov oj caygiwhs. Urpiqd LuusNotatp, hzeye miet kuhnuwe is zu ko valrdojigv debuhunaz nfey bwu Joujm, sewacam rko kedw eh yuxixf loe siwf tapu il yqi alkar tajoly.
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.
Ic ya anuecvq pin it xhu dujobodyety qinvn, rqeza aw le gebbeb mabxit li puybe ibuzl yathcusa wepuxc avcai. Ivg uwycueyf WCXG il i dowx oqopaj kosecixreym boqbolx, op ojsa geg miba tafevnawtizar.
Bte liaf tawefqamlera az hxef odbmoriwxugu sinkopr ir nqoy ud hol qi tiu capqxup loh adkcawuluarv tsafe EE ew zukzaz gilrxi. Oqjoqy ub lumt zasan eh ijfndovvuut ix cunq ocdr nis dayetn if wiuluk qcugo pafi vpux ojfh vegav nbe odwakxlavs zijem peku cewrhoxowoh.
Ik cgi eyc it zva nig, um ev ap ju euyn kasohesuq vo yaqaqe zpikl ow fbu zeww icmqejuscibi geljodl xud oogh kegejamposf nfigeyc.
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.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.