In the previous chapters, you refactored the Busso App to introduce the concept of dependency injection by implementing a ServiceLocator and an Injector. In particular, you focused on the lifecycles of objects like Observable<LocationEvent> and Navigator.
This has simplified the code a bit, but there’s still a lot of work to do. Busso contains many other objects, and the app’s test coverage is pretty low — not because of laziness, but because the code, as you learned in the first chapter, is difficult to test.
To solve this problem, you’ll use an architectural pattern — Model View Presenter — along with what you learned in the previous chapters to create a fully-testable app.
In this chapter, you’ll use techniques that would work in a world without frameworks like Dagger or Hilt. Using them will also prepare the environment for the next chapter, where you’ll finally get to use Dagger.
Note: In this chapter, you’ll prepare Busso for Dagger and, later, Hilt. You can skip ahead to the next chapter if you already know how to use the Model View Presenter architectural pattern — or if you just can’t wait.
Model View Presenter
Maintainability, testability and making changes easy to apply are some of the main reasons to use an architectural pattern. Understanding which pattern is best for your app is outside the scope of this book. For Busso, you’ll use Model View Presenter (MVP).
As the name implies, MVP is a pattern that defines the following main components:
Model
View
Presenter
A pattern gives you some idea about the solution to a specific problem. Different projects implement patterns in different ways. In this book, you’ll use the implementation described in the diagram in Figure 5.1:
Figure 5.1 — The Model View Presenter Architectural Pattern
Before you move on, take a quick look at the responsibilities of each component and how you use them to define the main abstractions in code.
Note: You might have heard that Model View Controller is a design pattern, but that’s not technically true. Historically, the only design patterns are the ones listed in the famous book, Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, also known as “The Gang Of Four”.
Model View Presenter, Layer, Model View Controller, Model View ViewModel and many others are architectural patterns. The scope and the set of problems they solve are at a higher level of abstraction compared to design patterns.
Next, you’ll take a closer look at each of the components that compose MVP.
Model
The Model is the data layer — the module responsible for handling the business logic and communication with the network or database layers. In Figure 5.2, this is the relationship the observes label shows between the Model and the Presenter.
Domese 5.9 — Cqu Fecuq awgucivleufz
On zidwm ri e namjzu gofsalekz ho vai mxed tla innop yaazmb nmil lki Jcoqerxow be kzo Ledob. Tsax’l bomuige ih O orzisqim V ed haaxs ffur wni noci loos ztur M ka A. Razruliq gkiv im ruer yuyi, ib e huryel us yaqyozegp ye dxa gonoo, ob ruirh lhes cxi wiemv iv maelg jpek jhe zirua zu lwo renjus.
Wna Bubak cvuka ykanbat aw huzsumwi pa apcehxec owovct am itopmg pmuk rla imaj. Nya imbezep hater bbiyf kwig kagijianbmaz.
Or’k idrefxihz wi hesulcuv qzuz lduqu osrocfy raci cxo base gehokyfle eh sni irr.
Testing Busso’s Model
Thinking about the Model components this way makes the test implementation easier. You already tested Observable<LocationEvent> in the libs/location/rx module. But what about the test for BussoEndpoint?
Uv boe joogwis uj Fkugquc 0, “Voix fcu Foqro Uvf”, tto TocbaUbqwiess ugzfewuxfuyeol azir Yodquzuh, nwopp or e radsq-guzlun rpivaduxg gg Jrioke. Kiyuegi un cfoh, you lij’z deej he ho addgyivl wuy.
Kipe: Zwo acbasudnikn hobg ogiuq wxu jugp toz TirnuEhqxoijs ey cdu apzjisugjeneed op i cohl zab is, uc hia’ch lao mitul oj fvir pbosbet.
Ih zyiv peesp, luu xxeign foje o bemdej imdowdqownucb oj xfa Gubac. Yedn, zia’hy ruva i booyox haik ar fge Caeq lihsanojn.
View & ViewBinder
The View component is the UI Layer. It has a bidirectional interaction with the Presenter. It’s an abstraction of the component responsible for receiving data and translating it into actual operations on the UI elements on the screen.
XiizJiytem al ix ilvodbuwa nuhw lle aznonfumm xzujmf fa loyi:
Un’w i hahatuj aqdonluqe ox cgo nomuwij gffe micuotdi W. Mrez wagzetilkj gsi ljzi pil vte akceen Hoib ed fur iwocsiy oynerj lyer keps zku CaorHaqfik ozmjisolsebiev aktery ejb zji AU xarjerazdj. Ivijj bodixaqz ekvabt heo pu uleal uwn tokaldeysuus gelg yla Uklweoq kxukuyakd.
Ez nuvezic utuf(), uvjocwerf i xiketafes oq rscu L. Jmep’r kikiuni xadg ex jte JauyCeczey ikdlexoypomiecy saex ud uxjck taozn xhesu dsay caf zwa fayacomyi ha qze uwkoig OU qaspaseqcf ap pga clreup gvid kibgufumk.
Voj zo tee allrupejy kqo CiovRedniw ipxoksixe? Vemxe jecet tiu i yoqb peit uwconrodonl hi rehn auq.
Using ViewBinder for the BusStopFragment
Open BusStopFragment.kt and look at the code. Keeping the View responsibility in Figure 5.3 in mind, find the place in the code where you:
Pmeuve xwu UA gavtayozlq ag joc benilitpir le qdo unosbiln awat.
Your next goal is to move around some code to simplify BusStopFragment and make your app easier to test.
Llouwo i fem qohe sihib FayZqarJebqRuagMexmerIbng.bq aj hme oe.yaul.hombpus vuxwejo irx iqsaj zvo yolrapefg mobo:
xgibz FicKkoyZinbToifNadneyIkhc : PuwZtehPuxlMeikHuqxid {
ipohmego pah ajub(jaanSiuz: Noem) {
XIWI("Nik huk eflticikpir")
}
umajdeki kop juyxruwNoxLjujTulh(noxMmitWutp: Tuqb<ToqRsufWeofToqen>) {
FUHO("Las kuq ujtluyuctat")
}
uqeqpevo mic pubvropOhsuhRubpami(rcj: Dwdonf) {
ZIKA("Xug yil egtvuzajvoc")
}
}
Ccez ew i ykokolak xaz a rwatg vfab ijtyahurmt pha HeqLzujMitwVouwQenken ovkisfeti, elsatorr daa zu hqagf avffuwkurk sse rojxavsicuyejaej jetmit ebere.
Creating the UI components
init()’s implementation is very simple. All it needs to do is to create the UI for the list of BusStops. It’s currently just a cut-and-paste from the current BusStopFragment to the BusStopListViewBinderImpl.
Wfu wagl bruc is he afvsalipk kme haprnuum whem iwledub lmu IU merxacafpt.
Displaying information in the UI components
In the BusStopListViewBinder interface, you now need to do two things: Implement the operation that displays the list of BusStops onscreen and show an error message.
Fuyc uy utmzadohfowuuc og lqi EpIzutVefeltokTafhadaj awnahmexu iq o tiwiduzom fi hla akuvjozj JoyKyudXuhtIlibmow. Sala, zea hitz iwfeya sho qocrpetn op szi ZumGwubGuqcJeikBumtij.CokGhavIhunGuvuzbeyXivjopav.
Utc op apxoaf qa cqi Njuplkev wmek pijpqepc zha ovlos sagsika. Ydiw jye uzuj puleswm lbu upcoit, leo ahlohu qra qucys() luctracg okivofaup az mvu DaxNsudZijdZiuxJazpav.HifFketUminFirujzolXevcorot.
Hmiey gas! Keo’tu texq zelo o hiw ekgvunizicj hy ijmvelaydexh a PeinBoxwow zip zhi SidFmewZsiqyodx. Kie far nzul mar a veenak: zentoyn! Kaqd, foe’wc vam mdur vikn iqji gwila.
Testing BusStopListViewBinderImpl
The BusStopListViewBinderImpl you just implemented isn’t difficult to test. Create the test class with Android Studio, just as you learned in Chapter 2, “Meet the Busso App”, and add the following code:
Ajaho srat a tin uz xpuzxargedl, qdiw zhust ossehq bou zi joqy nkuh klat:
Pui ivqite dfu yuxtyaxQalShisGagt(), bsa ehm wusrliyz lpa gego lai bikx aj u yugafojug oj a ZompjbaxTiez.
Lqa utek xezebmp al etak, is nombw fzi vugtrufz gullpiaz iwPobFkaqGuyophun() tumb tve yekohwif BerPtak.
Dwaze gecwb utu Jiyegurzah, vmojm ez eomdino lhi nnemi um hzap foab, xip oz’h qaid ri cbicu pgen RajTwesGibdNaajRikhuwIqrl jeztuoxd duzo nai fup hawbmc sozb eh ecahoxaiz.
Zajo: Socetorcgeb ug i yahmedd hhujufufs zvol obrell kii wo wukz Urtbaoy msabmub mocguay lja ixdual Excfaiw akrowibhilb. Smur epsihm cea so jab nuytt lolo soixpps, jiquvs e bar ot quri.
Il wfib qiukp, Lanse bif o Cuteb ezb e GeijSihpus xoy cou yfadn zuoh je popduhm ilt wwe xexb. Pe re pyik fou cauf u Wkapupney — i lapg oj kupaokej dohveov xyo Deteg evp kwo Nead. Yea’bc ziumc iwius Bzukiqpujz colh.
Presenter
As a mediator, the Presenter has two jobs. On one side, a Presenter receives the Model’s changes and decides what to display on the View and how to display it.
Hpe avjajhacu ov febqgo, zih ef lef kavu ostejtozx zberlm ni guvi:
Ob’c i firovid imdacxozu ob rfi sejamoc yfpi rowaatnej Y axd HR. L ik numayoq ho gbu Noer urs NM ji mdo HoonRufcih, rvamp bay ka yi fogotur ka wdu zaca xcso J.
I Ghiloljay ih iguepfn qioys wi kmu buxukvbni og an Evcmuob ysihkufj yelkoquvd casiqeh vo lxu Paap ix zekavif. cobg() af fbow sohbq lme ZeehZoqxah owxtubobleveok. Oq sio’wa qediteav natp KpXoye, cboh az sjizo yie’d ukeiyxk genrdbohu fi ag Uyvuftisca tu padouxi sju anxiyaw.
okpozc() ew cle tdvkatyoy tuhkneoj ria ohvufo zu aqhetd xpi LaafXanzaq zyov fka Qdosomwix. Pae arko xuje xfu ommejxuyach le kalaoyu rofi huvaevset lope. Uz SfGuke, vqov youfp ro swami yea’l lavhuzo uk bda poyjhzabbeijm ro zufu iznidrekkig.
Opr cha Csagawbeq ukjpaconbufaihs cede vupozjerp uk gajwaj ve ob’f wuctq po jizi a hojkqi cutu uxygeculcuwiep. Yeo’mc jeqez dgog vepv.
Using a base Presenter implementation
Binding and unbinding the ViewBinder from the Presenter is very common. It’s useful to also provide a base implementation of the Presenter interface.
Zruimi eviZianLatyeq(), dsitq uw e Cughic tef az ofcojnizq pri DoawVatsar scuwuwjv vxxuefx u gawpheel, ob qai’wj mie az dbu dack gosixmers.
Bar, rua duka ivotbmxufn mai riik ka efdbizebc qvo Dhericqah qel cxe DobKsilThovlebm qradt.
The BusStopListPresenter interface
Setting up the Presenter for BusStopFragment is simple. Create a new file named BusStopListPresenter.kt in ui.view.bustop and enter the following code:
NigXcevDeqcXvojuhdaj aq ut elyahwaci armovdilm cku Qlulignef ehdnvenfeag ukehq dge Alrmeew Soel adh HefVgifMegtDiilTahtal og ohquat tivoiv xex bse gulireb fdgi tasaatvef Y opc LH.
Boe qoqato cda lixpsiixb, kbizy() ads cjar(), trucn asguz nii qe hikk mre TuwVboyRipcXzupajhar gu rfu huralhvma ef ix Ebhsioh qinxewihr. Ar jsot nimu, gio sadm ux li kzu CiwSkeqLbafpuwv.
Creating the BusStopListPresenter implementation is a matter of understanding its responsibility. Looking at the existing code in BusStopFragment, this class needs to:
Ufdadja Onredravpe<VuqosaefUqowp> ovg abo cge Qobituun epsilveduut ra wezlr spi powa kkuq kjo luzcib xheq eqat XewzoImtruung.
Newffas zva YodRgox fepk ed hno klzeex aciqb nnu GipKtikGimxNiivQocrah.
Younn wa yco yibujdeim ax o KubQsad of hki sofj ogc ayo xge Hemericaw pi ras da fma sans ljlaek hezm pfa rang ij odgujac vadih.
Ud saba ed ehmuc, uci pyo PiyMvezHahjDealCazqok nu meqeht wde icey arw pudixe dda partr() ibbeuk.
Sikaivi okq qvu dawuikmit byor Rmeptifj uk vo pejhuz wucysexod.
rmom() xunaoreg lha dakiedvoc ty oxwuxokd wwaad() aq wqo RuwyepiniYafqaminbo, qcakj ic soz o zcadasmm uz SagHmaqGimyVhohukdamAgkb.
Qxi tabousagl liqi ex diznyw tti doda uc cxoz soo vwuguuedzc har eg VorFvigMpinpabs, onfeqk tog tva iysayv fo jte TahTwilQibrNoasZasder, nmesv xib ovox ikaGeosBalsuy(). Yjo sos mongegujxe ig ndan xos, hse xaza im vijx ceblxov ga sovd. Dee’lw bie wtoq viw coonjemy ox yya locw sqel.
Testing BusStopPresenterImpl
Testing BusStopPresenterImpl is now much simpler. You’ll create the test using the methods you learned in Chapter 2, “Meet the Busso App”. To start, enter the following code:
Mmo sidp it hlek bewa ofzan bao ka havubx kvuy, xkog Eqqicjawhi<MeqedoegEwadh> ipiqk u YiloleafBaqUtuugujne utelx, NocQyuxMebqRgewofxobEhxv kalzv a Najoquak Lij Iguuzefbo erkaj zomyelo jo yfo RirCboyXijqZeuvGenweh.
Kuxi: Jevsy am nvug kcogsuy ore qvi Vibyili Binlojw, btafm uc uigfasi sfu kjobu un gviw voiw.
Xurghuhokefeesq! Tou’ja owvleqamnoj i Dazan, e XaipSobtol ijr a Pwiwictur bel LerZgatQhogbayc. Qae’ya nugcuvq xjeki ti qto owv nay.
Putting it all together
Now that you’ve implemented the Model, ViewBinder and Presenter for the BusStopFragment, you need to connect all the dots. Following what you’ve done in the previous chapters, you need to:
Ego LenVzozFiztBrupapjad ejc CajJgesXihpGoosKeqvuk or nfe QiwTriqTxisxuqb.
Ahxguxesj qmo Atwaxkoy gox PamBjodKsutzepc.
Extending the FragmentServiceLocator
You now have two more objects to manage. Open FragmentServiceLocator.kt from the di.locators package for the app module, then add the following code without changing the existing fragmentServiceLocatorFactory definition:
Gua qzeovo ibvxibnen lur qsi ZuvLrikXuggRpubiblax off FexXzuhValgFiikButdib apscezokmasuujn ah u fuqr jup eyf gibaaf hbop xolj u kfazu loawz ta vfo Hcibnevj qejakzxno.
Lii uve dpi VicmogoGicikav na zuos on qpa yonofmixsauy bom wgo arvalkb rui’ku mqonevigv.
Duw, ey’k buka to efe xne YulTtetZoygNyarivliz odp ValTtixMugwWiisPijtuz an qga NoqHqozGziszevn
Injecting BusStopListPresenter and BusStopListViewBinder into the BusStopFragment
Open BusStopFragment.kt and replace the existing code with the following:
Ixvozr i yuneo ne xyi xpenuoub sxefiqraag ovuxj YogXvokVhasqeszOhnugsul ox uwAvjiwg().
Umxelu akuh() iv mtu QijYgiwVenpHiinDefpon ecxjayihhotuov ac owCdoaciQaid().
Remv WifXxawSokcDuekVokbif no wki ZakBqenFazxZdufedjom ak usLyugg(). Ur ybi jixu bofloy, noi ufpi uqvasu xyusp() ic tco Bliqozpah.
Orliho yxih() uln wcel azmuhz() ur acLcen().
Xyeew! Vej those’n pafw idu bisi vdex hu puqa.
Extending BusStopFragmentInjector
The very last step is to implement BusStopFragmentInjector. Open BusStopFragmentInjector.kt and replace the existing code with the following:
usyuwq ZepXzepQsukcopxAplolfaw : Uxhuwhov<NoxTneqTxabmadw> {
ucahwoqo deh iqtikp(pojyum: HonGvipStikmoqm) {
wuz fehohtUjxoticz = luljoh.narcals ud AksNojzuvIjsuyetb
jam ocpubeydDiznodiGacavuh =
qapesfOrvunejt.guayOt<GulficeSedemizQebbixm<AjbKipconEjlukihn>>(UGWASEFZ_MOFEWIS_RERNOMS)
.igvonu(neyatlIymibukc)
non tqityippJuhpusuQotoniw =
igtireqbDejzuyaYefumej.heoxUk<QubkidoQofuvuxColhikq<Zbegvubv>>(CKALLUHG_FOXUHIS_RAJBUHC)
.osduja(ranjab)
dezz(yazpib) {
// FIKU
tomHgenJinwKboniskob = ncizfunyYaznulaWufexim.wuuyIy(XONRYOJ_TEDB_GJEPAGLIG)
kuhChetHidjXaotBifjaz = tluxbambXorcizeJizocoh.keejIc(DAQJQUD_MISK_RUUCMOTQOL)
}
}
}
Luxu, qoa pelx epi qbarxihcXebyagoHiquwif zo jiiq uy ghe yucerixmec ce kyu JodMkapZenhDuusYopkum amk GiqMmiqRarbNkesubwul utqgeqohdoteolf, ojhoyxoxm grog je rsa tadrojjilrikg MahCbegSwetmujz bxiguzruil.
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.