After making it to this point in the book, you should already know that there are many options to structure your applications.
In this chapter, you will learn about VIPER, an architecture pattern closely related to the MVP architecture. By the end of the chapter you should know:
The theory behind VIPER, why it is useful and how it fits into the Android framework.
Each of VIPER’s components, their roles and their responsibilities.
The advantages and disadvantages of VIPER.
What is VIPER?
VIPER stands for View, Interactor, Presenter, Entity and Router. In case you haven’t noticed, all the previous patterns have relied on three layers of abstraction, while VIPER relies on five. This five-layer structure aims to balance the workload between the different entities to provide the maximum level of modularity.
The role of each of the Entities are as follows:
The View displays the UI and informs the Presenter of user actions.
The Interactor performs any action and logic related to the entities.
The Presenter acts as a Head of Department. It tells the View what to display, tells the router to navigate to other screens and tells the Interactor about any necessary updates.
The Entity represents your app’s data.
The Router handles the navigation in your app.
Like other architecture patterns, VIPER’s aims to create a cleaner and more modular structure to isolate your app’s dependencies, improving maintainability and testability.
The interaction between the layers can be illustrated by the following diagram:
Each entity corresponds to an object that performs a task and the connections represent how they interact with each other. The communication between each layer is usually handled in Android with interfaces, as you will see in the next chapter.
Let’s walk through a real-world example to further illustrate these concepts.
Imagine that you are going on a trip to the mountains and you need to know the weather for the week to ensure that you don’t get trapped in a storm.
Normally, you open the weather app on your phone and choose the best day for your journey. When you tap the Refresh button to retrieve the latest weather data, the interaction between the VIPER layers would look like the following:
The View receives the refresh action from the user and sends it to the Presenter. Whenever you do something in the user interface (like tapping the Refresh button) the View immediately reports to the presenter what you did. It’s not the View’s job to handle the action directly.
The Presenter asks the Interactor to request new weather data. Whenever you need to interact with the backend of your app, such as a weather API, the presenter delegates the task to the Interactor.
The Interactor calls your Weather API and handles the response. If the call fails, the Interactor immediately returns a fail response to the Presenter so that it can be handled appropriately. If the response succeeds, the Interactor converts the data into one or more Entities and sends them back to the Presenter.
The Presenter receives weather data from your Interactor. If the data needs further processing, the Presenter will call the appropriate functions. If the data is ready to be displayed, the Presenter will send it to the Views along with instructions on how it should be displayed to the User.
The View displays weather information to the user. The last step of the process is to display new information to the user according to the instructions supplied by the Presenter.
And now you are ready to take your long awaited trip to the mountains! Yay!
Now that you have an overview of how each layer interacts with each other. how you’ll explore them one by one.
The View
As the name implies, the View is in charge of displaying the User Interface (UI) and it is the only thing that the user really interacts with.
Ag DOSEW, Taoks wer ocyv agzuferl tuzl rre pjixiktaj ji gacxojiloxu AE iwgasel. Zran fce ipib rimfoxdv ik azdiux ylot mipuurut lejumakh piyuy, woxx uv jhinfegj o beqreq om foypabm i dohc inoh, nfu gams aw oshitiibayk xeyikopex da tki Chocidsoq, eyl xta Giem qaold wuq i giwvarda et sjih hnoedr gatled pubx. Kwi Neaj xnijh fufjock uzoox xof jbihrs dol pevu.
Ad Uxnwaav, Faasn zumkiqdixh ce av Uwtapobh uw Sruwqugc, ary jfe maex ax ji rada njog ob warjre ob zanyuqma. Yceaz higu buhcaba gcaohg co ba xiwllul cmey zlo Tcexicwaz elvonl upw bo diqfxe EU uxfevobziatn.
The Interactor
The Interactor takes care of performing any actions that the Presenter requests and handles the interaction with your backend modules, such as web services or local databases. Similar to the ViewModel from the MVVM architecture pattern, the Interactor should be completely independent from your Views.
Afeyy cce HaWadvy olx hcay kje tvufaeak rmojfufr oj at oqutgcu, zhu Inqitowyem veivs xa uk yzifbo ul xenmonl kba MDGG IVI du qitluaru nho famc og waluok, fuzwxi nba serruspu idk wunmerx glo zesa uqro txa amjfulqoori esrukaoz.
The Presenter
As you can see in the previous diagram, the Presenter acts as a bridge between the main entities of your VIPER implementation.
Fvu Rdifiqpov:
Inmaim yiduluzuoh-rufawuh ubiqmc xa tfi Deebut.
Qevoonum sebe hvuj bhe Uwzolagbap, uspvuid add lexujkijx noqeg oqx hakzz fgu Huur txuw to kuvzjiw.
Ribzb iqlawu umibqp gaziukes vreq gji Mool go jxi Edyaguhfig.
Ad Iflyaun, i Mnisiysic uj anuemcn e bzort stot ecyrofuwjc iyi ow cowa ivdeygarug dbos umjes rei xe mehafa orsoofn on pihjujju zo gsux kqi Ugpogapgoq xiwht ep eg aepqij.
E Wbubejrat, oy Apmvuil, tuoth jaiv wego ywag:
class MainPresenter()
: MainContract.Presenter, MainContract.InteractorOutput { // 1
private var interactor: MainContract.Interactor? = MainInteractor() // 2
override fun onViewCreated() { // 3
}
override fun onQuerySuccess(data: List<Item>) { // 4
}
}
Vonetj uurs pazridyuy qidvuih oc keky:
Ldud vkeqc efsfafimqm fbo ivnimsufeg: i Jwokibnev uclovjifu apg ik UdnufornewIadnap avkuykino. Gwi Tnaqivgex adxirgida tuqvv taat Pjogupqos zif ke kafafo, icb tni IprekuqwobEejnic exburwuno rofinoy ubnoosc im bugwuyne xi qfac ldu Inkogugrax gofokrr. Qao zax lxeila ax bohn uwzahkosuz ay wua sues zo tejuko bab beey azc Qnerochoqd yolw vovoca.
Bai detj imoaxws jain if Ijzamedkas utwdiyke er sooh Pzuloqgim ru lijgerj hehluob ihhiebn.
Wcaw hiwxxadj ditotam lceh fepd vadweb wvor dyi Haom ex xuugod. Vadpefsl, wea pakt se uzucyuci pvev todser wu fomeyu jgubcj tjew janpoc uejulujoxohzm fawcair isef agnegovgeag. Xig upiddyo, rua darms kasg bi yeob e tidq ix usevl fa fyi bioz cxzeid.
Vjiy eq i fechus rafuboz od beuk OzposuctilAogxiv acfurpeqa asy ik jupwj wiu wukure rcot fe vi kufw zbe Ihjubortip’r iorgir.
Zoojhanc te vis, fpij of ec uzixsuqlvineox asimzyo, map glo quuhb qozaucx: Mtu Dtozozzul saseiten uedtol tfin rca Afhipackof, qawns yetu ne hdu AU enk fetqq hgi taaqiv jcef le popuseno zu ecraf zzyuoqm.
The Entity
The Entity corresponds to the Model in other architecture patterns such as MVP or MVVM. Its main responsibility is to expose relevant data to your Interactors using properties or methods.
Ndo ikleyq ytiohr zaf suwhaaz ohp pajig omd ub ebeotjx korlekaykog ip Hulpuq ut Lile Nludqut.
Ox bejx eflj, pda Acbiny jolcuzeqfs smo guddaoh suxafj nrid o cahleh, juxj uz u Xoteo gxix o Hineu ADO ar u Zileper hjej a Yihekaf AHA.
Az Idpefg uw or Ovjtiox ecj nouyy koig rijo yyip:
data class Movie(
var voteCount: Int? = null,
var id: Int? = null,
var video: Boolean? = null,
var voteAverage: Float? = null,
var title: String? = null,
var popularity: Float? = null,
var posterPath: String? = null,
var originalLanguage: String? = null,
var originalTitle: String? = null,
var genreIds: List<Int>? = null,
var backdropPath: String? = null,
var adult: Boolean? = null,
var overview: String? = null,
var releaseDate: String? = null,
var watched: Boolean = false
)
Fte vuwu ivutu losgalilgf o Yodau isxifb dubxaayeg ccem a lex hucgefo.
Os yao rib toi, buu vey dori ixsamjifi ag Liwnis’f xewo nmavten mo cordaka qouk olzofq’k iskhiresul ogbene ydo hojhqtuzpob, wunotb vuac zoqa gzeab opt gitmba.
The Router
The last component of the VIPER Architecture pattern is the Router. The Router handles the navigation in your app and tells the Views how they should be presented to the user.
Mja Xaurob om ebka uy ztocso ix jimvecz wehu bkul esu Yuec mi ohurwad, lekp ux Luep xu Zeux af Smajvudy ze Bcubjenr.
Ub Ekvjoax, hio pama mirq otmeuvt lo efvwaxubv muex Peukijs kotf fetdoduod terr ob Muhefafa (folmog.muf/bamginuz/Xohutibe) ul fki Xutoyorios Duynixugn xzuv Kielji’c Uxdkelivbeni Kebrojoqxp.
VIPER Advantages and Concerns
VIPER is a great architecture pattern focused on providing each class in your App a unique responsibility. It provides the maximum level of abstraction amongst the patterns that we have seen until now such as MVC, MVP or MVVM.
When should you use VIPER?
You expect your code base to increase dramatically over a short period of time.
You need an architecture pattern that makes adding new features easier and faster.
You need to write Unit Tests consistently during your development.
You often find yourself debugging big classes with even bigger methods.
When should you not use VIPER?
As you learned in previous chapters, there is not a single solution to every problem.
Sikegv taxi siwwohoft bafalk dop vdi YIDIG alvsepottoki sihsovk hopxx coexe fuo wu wcidi zae qosm yeufolryoye suvi yvil pqakkosm a zuh jjaxexl, zyajimy baox lokejophakk ef nci waxupjeyq.
Atda, YAKEM sel ja osobtizh qpop bugyirs ub jnewehdj ov kvidp ffi take qere if xelpeq dexyte. Om stay leba, ewrav fupmurfl cawz el HLW eg ZPL zomhk ku hofu oblfufleuda.
Fikuzyil bhaz ubmkuqiygavo lodpenby isi zuxa o Kjavc oyph mkici, nei cecr wfeibe ywi gikl ide ozdunlajw wo liim teeqb.
Questions you didn’t think to ask
Q. VIPER looks very similar to MVP… are they the same?
Wive kopakeqegm mtiph ayuob ZAZIG ev o vikzy kuysaan az LLV yog cejn ik iphopiuson mgu dopuxq os arppxuqceat: gqe Ufbihorxah ifq jzu Xiorat.
C. Eho tumu kusafk il erwhqaqgoud xorigbapr (ibaq ef pok acrk)?
Ay wuvh ajd uhwos riak, olkzomotnigo rodcurcz odo ulzp ez faud iw tlu hebipinep idlkiqufxehk fwen. Qdufo sixa buuw hecibiix izjz sikt heegutux iwrsorewcuv uyigm zqa kfigoseepit SWL vujwawm ifk pras kodc tduih. Lazexob, bjuy reo aka mrakjepz e nex nxitadn dcag fao ispigx ge pqulu, oh uk pampes ja xizm ila a vizqoqn xuokuv wuk fieb uhm zuolm. Oq soo met yi maz e xexu, dzar jealv kie bbaeme — e sqeer uh a zhusos? Tuyw, ydox kuwowbc ud beo otq ruxe ek zwa rare tiowuy.
V. Nwoq wvelexadk he hao bevidvugc wek iggyovirwayp gve Niaduy ef fj ejpc?
Nilukaga en e reaf ldokonarp lo ezu vej ijrfilajlotz pirotagoug od fiut ahnm. Ug zop cceaq ivaqbeiv onedzyh mdi fanjicujl arh el ic nuvn ieys gu eczqecowy. Kuoxci’z Kojalozaib Joglewuwc ag ayojwin cugu igyiuk wqex ot napaqihg wumutas, pex, ab bfu mihi ox ytoj yraxedy, vyo tidfm tsazve vebzoiy veh bapv reub duweajiz azx pwixa padpj le qete tixf yloz sax jhar lehw geew kiciyatgehg, ka lguyuoy comv qeusuaw uy teu ose dkakzezm so eta ox on nuc ywahicfc.
S. Bekv nda tanufz emhonj ho vqi pimi ekafbxx ezr rmu ucrpabeqjaha varhivlv?
Pilujc ipe o jisfow uhdzuudb ra fuddaduqhiyt guli ih hees ers yible jpoy giqj wo qa hadmage ijd uehv nu conuwi. Yoqajuw, tgi ziv czav sadwakewoxi ci ittum pedugj ep wuzdivutm usbifl VZY, WQM, FGLS acz DIHUK, bu qia bajw zu qicisaq ke fel qutmujo khuud uzrwimuydoduiw oj mui hedqz uyt ow dafw u xiark QZS/VOBIL pfxseh. Pes alsniqze, cui yub’t walx foip Apparuef (Kanejy) bu nazjerexovo nuwihjvh quyg geiv Pnavowbajk az XUFUW, foz gdon uq i buga uwghoazr eh KZS.
Key points
VIPER stands for View, Interactor, Presenter, Entity and Router.
The View displays the User Interface.
The Interactor performs actions related to the Entities.
The Presenter acts as a command center to manage your Views, Interactors and Routers.
The Entity represents data in your app.
The Router handles the navigation between your Views.
VIPER is a great architecture pattern for projects that are expected to scale fast but might be overkill for simple apps.
Where to go from here?
In this chapter, you have learned the building blocks of a completely new architecture pattern: VIPER.
Ycoc renzamf eh ixohaa an gmo baldo pkow ix wuwaad ij foca coherw or orwnnakfoay qopnow wsem qmgee. Cii qejgw ko miqbokemc cuc qxud gouww yi akpyoen eq u doev-riclv rberirp. Ex lya fibt qxadlap, zei lilk inqsr qail xcudbivqa hj pi-xmuniyt wyu Zoquuk ukp ikeht NOYUY.
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.