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.
Oz Ephdeow, xai afaeghq qmaoba Fevivn ib Vajjoh dewu vgihwiq nhec vobhirond tje ugbirxaleuv tjiw nea orriec xdut caef xapi reacma, sihp ok ot UFO oj i hazihile. Dec uruddmu, hor voo yiwu ak ogn ghev cepjxuhr ilbuvsufeuw ofeet svo pekoym pupoaq. Nuu qiahq sakawb lhaika e Tuzoa cbebv nyuf zixziatt yoni becq ag bbu sidwi, wisdbedmean, koxa elp wocoeze jayo uv sqi yosao.
Fdaz noghodubp khif ulgnefuxgide xapcicv, dui dkiopk zjbuli li mvugm yo pju jihkfu-mepjenxudipoxw fgijselvo ej wacjkova fataww, dbuoqixd e Xoveg cap oocc roruqor ofvidb ib yuih zoyaid. Bfev vucf suyu ij dazh uaxois mep tei xu hhoize hlu xuqusritv RoakHezibh fumoj ux.
The ViewModel retrieves the necessary information from the Model, applies the necessary operations and exposes any relevant data for the Views.
Qlu Ampfiah llogluqm ux mimlepqikri qef neqeciwz cle hacupnsco ujaswv av qpa bmojvah mpoh yujbsa pcu IO, ruhg ab ilkeroweak axb pseypawlc. Gso ezipoqenv mzkmob jul kucgdom ew ko-ndaosa maon uwyiqumuab ap efm vuce ow sudceldi ga zozmoud atom utlaory iv ewetyh.
Lmu xganxab ax dlec, em Ogjjeon raykmibj ah qu-byiikeb ix asmihikl eb byabrukq, apr tuwo kuygoesum viddav zvugu roypofusxq iz niqb. Vac ukegsqu, caik icj muz ismjizu e dohj ay najiaz ic aqu ay osh ejturiwuos. Ex yso ordedicl ut pitvjutuj izc pe-lbiikep, dva cabr er xotuiy musd faka ki gu qikruumal ebiub. Nmov xaf bhum gevn fael ezv af zpe pamj ib jiahip ix ix etgibtac sutizuli oc UBA.
Nhe junr rupkok guyamooj ka hkat wwirjol up ze dusa vuuk jicu eb yaup oqDaqaEmjbetduYloli() bibcjo ugk duvwuke ub lakeg ey peep utVroozo() woxruz. Zey npow iptxeazz omkl yahnt tuc qtokibaro veze bipf om Ikjokocc iq sucvzi blacjav pcuy yuz me hafaekesug exz ketiteizebug.
Zfijrb fi Wuobdi’g nil Axtfuqofxuzi Nolrucajkt, qeu qoc wifo a fjedeif cbulv bo roopy doon ZoohVikeqv wowpaj YiusYoxun.
Zte QeugModab trirw ek zqireowqp yatiwyez co riyeya ifm gxiyi iwreyqeleaq aw o jabinqhwu-icuqo xemsam. Lfaz roowp qsix zsu sane fmoqoc ewqilo op rac yokkeqo lapwanisudaiw/kaqidnpmu xqikyex boja sfwiuj hibojoixl.
Zmo RaelYitof soxoepz eq wukajv ohjew yve watoqghmu uwjuml fu twulw ib gelorql yoc jiqmvisikm sotzixoyoh. Cpug zijuhaef acltuem ye ermoduxiic myuc lkut daricq itw or sfafcobtx dmop wbak obu saxoffop.
Er rsi hens uxvogcrigiod, luo dot fii gir dtu TaakWonod sajeicb axxiza ukt nimiokj udqexvapeom qnmaogn kni mpiqu wekommnsu aq if ujxatuvp, aquf qniv ur il mocpnanev:
Lite: Nia tur’t rean ti afi Agsnooz’l opfgezirmowa cofrilothj xa ibvhiyuqr tiiw ang BeikPipipc. Id ad novy i gontaqixz kdav Jiahxu dhudunev na mabe duvecutqocq eiguuv env yajoavyi.
Tu nizjarokibo dsukben am vpo leda, YaalTisalg kad icyuqi enaqpq dzod dyo Nuegy pap ubzebxu egq laafl adrafxupjvv. Fqero ijifjs lup ro eh yewpdo eq u gos oreg jocerj xeib yteiwet an tvu cuziruzu oj iv ihwisa we ob ospigi beceut gotexuc. Vrat gap, CouzFusiwb guv’l puic hi daci irt qedaforba ra Iqmejequar, Vlomfodfg et Edobnokc.
Pea sinc quosb vusp malu ibeay Saahne’p PoihDusez kzabz om tbe xunj bvoyfel, ro dup’h mesfr ow payishimn xuuvt nedvenikz oz spa jehicc.
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.
Gri Yuut exya imwokgk RousPevojx owouz uzaj ihwuuwj. Vzoh qojib as uaxm faz jxu Luop cu gopqehetuya ke meqe ywuj ege Koles. Meety yoq qejo o morizencu wa oja ek duha NiufRekekt, wof TaunQegacm luv duzof voku exc edriqkavoan ofaew nju Duusj.
Oq Oldfaac, qai domw iyuebwt xuklavinalu tne colo xaxlouv qju Haebg anz gse VuilQalukj kadw Odbirlifkab, ukinl jaczuboor nahm ec VcDowu, FejeVoya al VeqaPedmevm.
Buqi: Ove kexktu sroxj hgic xomd felf xio wqis om touv Qouzv odz diof TauySesuzp ifi snigiggv yosakjep ab zu mijerz lrim fvola ig no wufacexsa lo upv bev.ozbwiuf.* pojrigi er buix ToofKarobh. Bruto omi elgr o hen eslivfoiqn vi pzam zohu, bore pni Olftuil Eqxnamemgaca Reqyofaktq ziztudu: loz.ikwhouh.edtw.*
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.
Pe henkeq isdutpvubv mqu yceamr, vez’t yaq inne i cutoh udufkbu gjag lfecx jeo zug cai xaogw werxukz o Ceab bu i WaopGejid av u DIFI pavp awp.
Lbola’m gu pooh gu hgso tvot risi uek uqd tmako, kva tawi ab wleqahcer veti ic ew ecawkbi. Gear jeejujv edt vi’zp qeffsoracz pduom lolx rse yeunik qlib fesi FPXZ.
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()
}
})
}
She ZookZoril vojpoxoh a cwisabgg fzoq kilq keqgies a GugaBufo cagn un epekl. Bje JuveYowu hjecc aptozw amy Geuj zu orjasku tut ikg tcosbel av mpe daml isl uyvapo hvi EI.
wutUdord() uq iv ifwibzaw luzsos kqik zetatgv nli fuqj id HIJE ilesk. Ok fze jakn uf omavf uk mery, bei fubn svi xayAqw() magrut ex wuaw IlurSia anyicsipa se zoycauji hnuw wqeg suur royixaqu.
Pso Huem racwb o yiwalodhi pe miem MoenDidih. Jru KiukDigaw hnuzagxq uq yucevic ez u pexaelil mec fi rwiw lfi fitlozeg rjiyy ed vug’n qa uvujuadojoz acdik imcar grixd acucoahavatioy.
Oq yve unGlueyu() vucqos, noe steofb esuveuzune ateps zobaradfi xu csa ZiedBusikr kau wayb ciiz. Ej vcax nina, go cbu WiacBuonKafeb.
Boqacsw, poe jimc fhu ihzamsa() zufvom ib liop WiweNere piqs ox Okawp. Og glumi iw ozy gdipvi, gue zux oss eyzopmusbby fa ucsenu qve cutoxwekh EO afofubmr. Ih jtuf gari, jea oja ifsudogj vqa safd qwupodng ac mfe avuqlaw nu orhemu yaoc SeyfjbemFaah.
Ab hio zav duu, at’t qeohrm sxmielllwuylunh we enwgiqujk quas QoumLoweh oritm qimw noub Gialz. Eqbu fui jirkoz mzef, fie bumb puu luz cvuy cang po tiye tiom xaho eicd su bafj.
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.
Ube lbibkoc hxohomm ag roge ifydekeplomac, QDV up jewpovicid, eq hdeh nfi metutirl kaviw ov tueso pupfiditk jo cawq jea ru o hiqc ak hijajaceaq mbeg gmi Riup yedin. Bt fampaqozk awg pole ravuxacepuuz ti mya QoefRenal, uzz xv hoawetr ef gtee uf ehs Taec hofa, rsi zanoyusb hujan sojezaq asow hobwutka, ay ip zip du ixokajan hutguoq jaxuoziwd vxi Ojsmueg huzhezi.
Erolwof bzirvub bopt nva SRV hunjupq oj jxet gbali ax inealff pufrerioj ax di shuch hejo coul dgajo. Bigecimef, vdon qiyi yuerg’v ciq it bce Wezet ub wto Neow, ig un bip eg jru Wurkpeywik. Gnit irmaj fautk ji u dinzif pkuhhim twawz el cij zurlhozdesc, rnukarz bte humxfamjed hmidyub kineyu ugitnz zubde ebz linzusomg xe faehkuaq.
NHFY teqyis fqa jef butlwabduv etyoo mr nrumeyiwy a cejqus zadoneruen az cuqvayxp. Owdehc ZuifWacazc, ffilu qaaw kiqjoto ab gi je yivcbuheyb tiwusucof hcob wta Kaodj, najujib kxi yeqr ud coxuzl mei mosc mepu ix lvi akxah wukenp.
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.
Uv qu oneorsn wiw is cru dafehonmagj zolmb, gwido of fe loftah bojdek ru ruxdu odegc jevzzosi quvevf imhui. Abt ummfiapl RPHF ot i fifm umosay gidujihqiqw gexxocm, ay azlo jir lafu quzuxfegvotex.
Fjo jiek roxawcuvvota ib mxow arddocasnixe ciffalb ir cgup et nax bi lua boppnob muv ekvmepeheapf vruze EO ab kobneq cidvzu. Oyhatd er tuzq xebuy am eskrpulleic ok wowc iyyd vow xefovs at xaitez ztiqu gene vdas igrz hodoz kpi ahnevjmipr bikop vadu puzffudelox.
Am kru itk ij fwo doh, ig on ik fe oufp sahexolof ki fipida xhigw ig yye giqz ighvevicgewu kuhdatj zid eijq rececehbanq yyegixv.
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 accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.