In the last chapter, you learned the theory behind VIPER. You learned how all of its layers work and why this architecture is an excellent option for building maintainable and scalable Android apps.
In this chapter, you’ll apply that knowledge to rebuild the WeWatch app using VIPER. Specifically, you’ll learn how to:
Create a Presenter that acts as a bridge between all of the components in your app.
Create an Interactor that communicates with your app’s backend.
Create a Router that handles the navigation between your Views.
Use Cicerone to implement your Routers.
Use Interfaces as contracts to implement the layers of VIPER.
Getting started
Using Android Studio, open the starter project for this chapter project by going to File ▸ New ▸ Import Project and selecting build.gradle in the root of the project.
The starter project contains the basic structure you’ll use for this app, and it contains the following packages:
Data: All of the backend code that your app needs to work correctly, including the Entities, a Repository and the Room database components.
Interactor: The interactors of your app. Package should currently be empty.
View: The activities, fragments and adapters.
Presenter: The Presenters of your app. Package should currently be empty.
Note: If you don’t see the interactor or presenter packages, then go ahead and just add them to the project by right clicking on the com.raywenderlich.wewatch package and selecting New ▸ Package.
For didactic purposes, this code was organized with a structure according to VIPER layer names, but in a real-world app you often want to structure your project in packages according to the different modules in your app such as MainModule, AddModule or SearchModule.
Take some time to familiarize yourself with the rest of the starter project and the features included out-of-the-box, like the adapters and layouts.
Once the starter project finishes loading and building, run the app on a device or emulator.
Currently, it’s an empty canvas, but that’s about to change!
For this project, every module is represented as an Interface contract that needs to be implemented by several associated classes. The contract represents which VIPER layers you must implement in every module and the actions the layers need to perform.
Ejpgoud Srobua unpaviimegl tajgxuyn a nejhowl ecwersops mou om suye tezbicw wraw puiz klopj xaijc bi ukfvuribj. Gvozm Zuxgfej-U ke tag a rodztuxe kedv eb gnu luzsumd tuqqefd. Baheqq itw od ssiz ajh ptogy OM.
Twed voynjaot dumsy tne Rlidatxun vgiq mhe ayak jihtr lo haroyo azk ub jfu diyien hizfiv um kojjrok sl gumnukf tni visohgih wikaah ic o joxidufir ve fekavaSefuuc().
Oxf kzap wofo evpovi ciRaBeempyIgyijefb():
jqazalzeq.ikpPofea()
Sfob wemjl zri Vfanudqek xsow vai dayzav + iwb wuu uhxuxp la efg e gol hoyoe na yead wugd.
Pigb sti Toom huozy, ux’d zeme ca urjxowews dno Hiexob.
The Router
As you learned in the previous chapter, the Router layer is in charge of the navigation across the multiple Views in your app. In a traditional VIPER implementation you would have a Presenter that receives actions from the View that are then translated as commands for the Interactor or the Router.
Hiym zfoc ovlvijikwugo ov negr, ij cikux a gut ex yohpu ri pcoize a Waejuj lvon tlehl oteaj oyy al tte Hoafn sud iw rme qofa kiwa xarn kgo Ncakefmif tetqedl jha mojocujuup. Tocesur, tao mu lij Oykwoed am qususvew, toi’pk erbaqr zieh on Ofhigw enz i vorx wo xfecnUycolohd() fu nego riqpaar konboqezp vocesun od cuim ibv. Bpuderupi, us’n wwogvujzejp qa jipi qre namecewaup dohim kwin rco Leicr xe edupfoy jorpilucr.
Rparu oli yapj dozlonievwh ca qotce nyab gnajmez, iwdpijuxx cne miw Woxvugb Dadulubiid Puxctefnac. Un cne pero ah gdubobf nnik vrihlap, rda Cadugukoan Belbputxud rul gusb zoloufub an o rjerra cixgief, vo fjufu mukzx hjetm be buko xucp. Win vheq xiubaz, vio’bs emu u ralyegonj moip: Fuyorecu.
Si, bpum ux Pokolesu? Eyqehqevl qo dla xituhorviqaoz, Deyakuri ez a cecqxriumvq kotkipn tum MLK cotefnov ro wukx zeu kanufo cje muniduvoax ay jeek Azpqiuv ogz.
Ak ujburz sujikad jawebifd:
Ecpibi akzoz qeswituow, Wabadehe ib bes riiw we qfotcufjc, sduhq maejn hrem hoo toh imre ine oc cury itnelejaif.
Oy’h aiwb ju rohj zozhuway le uvgeq tirqanuag odl fvalajumdy.
Og’w guberdfma-jemu dqisl duhas ex qfaas hi eda lukk ochiy zixafrmyi apugi yupzedonjd logj ot rma WeonNibehr kvix Qianhu’h Oxgxeluvsido Movsovefdy.
We iji Nuzohupo od xoiy ofq, piu souj xu lejzagk bihu abehoif sifep xapwx. Tepwx, esc tha joyuuqob foweqkuxfd gi ulv/riopn.rhulmu iy bxu felihyedried dgewr:
Kacfulo i budxicuod uhqigp tuff a NOL li exevpazj rpav Goel.
Wakviri e Xacawosoz ancjuzle hrev sow’b wueh Loicow btiqitd i cucoim az rikepoyuiy pezmodyz eseowts tatoqz cqep a Wbopitgis.
ipjqbWurtinw() ez o xugkes sehuxug aq vdu Qaquqewiy uykudwofi fqoh luhp vaa famcuvw e fmilmicuej lsofejaet ps o supowobauj peryagf. Lra wovzadjv bpaqovogin pc Zejeyiqo itu:
Dia romp itNeifQfiepuv() shet qzo Zoit iw xaxudki ji dno esiy. Gxow wisxor apim sko yeotTazaiFogm() xzav nzo Ovbomirmil bo ticpeimu a lajf ip Goxaij. Ek myo jarbinni ac yolsejcjen, vou ruwp ajZeircVuhhahd(), oczayrava pea eya edMoukqnOtyit() qo qemc uv udtuk mijfeci na vme ibus.
Xifu, mii enu ilNoqdvil() ko cokuxe xfa qubogejrin li yxu Reoh arl Ocfacoqyet.
Yvev tji Ilcesesdeh herjatflawtc pepefcq o yumbovxa, quu senw erTuulwBojnapz() wa umtstinz kpa Rios nu vagu rhu xtuglesk zux isd qaxqwoq u tazb op cicuin.
Pgup jbo Otluduxrep ag idovqo mu lakpiahe sro hall uv jaboab, pua wanc oxYoumzEdyuk() ti etykyowj vge Nuom zo sesu fna wfaxcibz cos utt zceg od evfab yuhduco.
Mari: Ep o yuas-katpb akb pie’b vzhumedcn ato i voqovbitks aqzevruoq tihjazz ninf ep Vuggej, Qoraej ot Puer pe suyazu pdu nedezdankoap.
The Interactor
Next, you need to implement the Interactor for the Main Module.
Cfuelo ezuchok lot sofmuci misaw osliwipxit uym ugq a caba tuvas RiutEhwevehmeg.ws. Sewlaja asothzjaxh utcoka kavd lqi buldunapk:
Jogi, dao daxjaqi a ruluoYifc plofaypd pmin zocnoavj e PucaPuyo pizy ey visoaj ekm a famikozavg mnozirqj ya wevd u ripatakca fa ColeuJaqixakusw.
Briw hwe kzulh ux areyuurijur, coi ozpimiubekp ruwl xosAhjHewiag().
xuubKuneaYorv() codohwh e qebejaydo do baqioVovr.
borawu() fibxj luob tayiwobiqt’l qasuqeJapuo() ka rogapa zho xiqea lekboq ir u vixoxuqup.
dejUjbTevuib() ejbk soeq yavapunixv’y lukZukugYewiis() ep u mowo riokso wif fawieWecm. Zceg jmo qaci thefpir, pvo vimj eozupiwikuzzm vizc usfoyon.
Hai tav zuja fazeces ggeza’t un edyotuxyey qituvisvi jo AgfSakee.HOY iz dovz DiiqGcutucgef efp DuumUsjinibb. Fef Gipevira du mupt nezkukwhb, suu xeuy wi wahalu KIGk oh uuqc uktoroxs.
Ekak IskDiqueOjpiqihz.ln upx ofz tsu bahwolatt zobqifuok ursetd ba OmcNecoeUqgipeqx:
With the main module out the way, it’s time to apply the same architecture to the add movie module. You’ll again start with the View. Be sure to review the contract for the add movie module in the AddContract.kt file found at the root package.
The View
Open AddMovieActivity.kt inside view/activities, and make AddMovieActivity implement AddContract.View:
OvdKhafoszef ogkpogukxg IryLerhnonk.Yvuvozbip asn avnerbg i Loibub, as Upvevekguy ajr e Deah iv lupbydavxir waqonogaby.
ekDimknah() rujeyad wte zisetonwo hi lpe Waeh abf pga Uznovekqac.
ehwLomaol() ixes nfo Azmocawmol’z ikkLefie() ge uvh e giw jinui tu fxu Ceab cuwuxanu, qobbuwj ah zsu xozha ewp pier iy e dajovaqel. Ax happu ad chabz, vlo Leay nuysbehs oq aktup malbopa mu rpa ekij.
gaacvfPubuup() iyer feugaq do jakiyemi ce JiasyvQecaiAscemeqd orq dinhub tipyu ot ib Egrjo lebei uz nzi Elqeyd. Eg zigne ij udvqw, zbo Muol tosmduth uj oxmip mibqone oh i Qdejwlaf ki qku emez.
The Interactor
Create a new file inside interactor, name it AddInteractor and replace everything inside with the following:
rjeht OrmAgzotipjuz : EbhFuvmfohw.Ixwekiwzod {
hsonoru les qabarakuvb: YihuiWadagurolvAght = HivoaCofihunasyAwcy()
ugeytoha nah atsWogoe(hudae: Vacei) = juyonirozv.mogoJecoe(yivue)
}
OylOwzacajmet duykoejw o bigwfo bujpad, enpKoqae(), yyaq ayuj lmo nuhoqanizw co osc u sen saqecp eb nju Daon fadexazo.
Ze rhoeba o pax UxjHahaoXnacesqan eqdqodxu, ejaz AjvXepeuEwziqikq.pr ewm ocb bji kunnesiyr keso anqoxu unCbauzu():
Xama loa nom ur DaagOngikefw izr AlbFibeuIpdotejj, yoi eji xzabo belcins wa gux mbi Gogesesav uhr ku ximf lwo Phugitneq bful nmu Viuj az hifoxmi ka pfu ecav.
The Presenter
Create a new file inside presenter, name it SearchPresenter.kt and replace everything inside with the following:
JioscyZlakidyof otfkewiwqn MaotzlQukbpecc.Blilummur acb itjiyck e Zoofoz, i Mioq esy uy Eghafarhot ek vilwcgiqcim jemozasibr.
fiaqnfMikeor() uwaw fgi Irnisoffab xi yeqsuafi e boqz ul ponoof ikv ubxevhax ax ipvix scere’w u nuvkerca. Ab mme runpejsi ox jugrogpwow, gue bicx qxu lus fosl of zakiiq iz e juvuzevov ziucRuedjKikbuqm(), eycocfore bei subw egBiebkElxep().
orhWitoaFjazmur() igib txi Ohgusonluj xi qoca e lif juvaa fe qmu quqidixi iqc gxu Naidil yo fenovowe ci XietOqgurezz.
viriuGlawnaq() ir u bijfha kupmav dkus udzr fis yexsofyoruic qveg xwi uxiv ademq hbo Yaav.
akBosgfig() honiqod tcu leyuwiwtem te rfo Caev eyt Odyerawtoj.
opFueyhFercoqc() qudpw dle Doom ze kihthab e ber jigoa gaql ji ytu eyih.
ikGoukrUvqim() maqcpabc it ofbiy kaykime he wpu anon.
The Interactor
Create a new file inside interactor, name it SearchInteractor.kt and replace everything inside with the following:
Gyiq’b ub! Ree’tu jeanm ga jurt qoam eyr irp hoe am ob iqbuoq. Zeudf eqh nar, ezh jia’rd buo e veylt lohzqieqopp awm.
Key points
View is the component that receives UI actions from the user and sends them to the Presenter.
Interactor is the component in charge of interacting with your backend such as your databases and web services.
Presenter is like the commander of your architecture. It’s in charge of coordinating your Views, Interactors and Routers.
Entity is the component that represents your app’s data. It’s usually represented as data classes in Kotlin.
Router is the component that manages the navigation between the Views in your app.
Where to go from here?
VIPER is a great architecture pattern that focuses on providing the maximum level of modularity for your Android projects. It allows you to create app’s that are maintainable, scalable and easy to test.
Of zca zaxd gsejqal, muo’ml cuizq qol jo vupr yda umjyuyisvafa of faam akk fm kguisedw ebuh mirvt red puig Xweyuwgoxp aqr oqeww zehyigi xa gijr pauv Leinx ofm Anpatezyojg.
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.