In the previous chapters, you learned how to deal with @Modules in Dagger. You learned how a @Module helps you structure the code of your app and how you can use them to control the way Dagger creates instances of the objects in the dependency graph.
You also had the opportunity to meet the most important concept in Dagger: the @Component. You learned that a @Component defines the factory methods for the objects in your app’s dependency graph. When you get a reference to an object using a @Component’s factory method, you’re confident that Dagger has resolved all its dependencies. You saw this in both the simple Server-Repository example and in the more complex RaySequence app.
In this chapter, you’ll go back to working on the Busso App. You’ll learn how to:
Migrate the existing ServiceLocators and Injectors to Dagger’s equivalent @Modules and @Components.
Provide existing objects with a customized Builder for the @Component using @Component.Builder.
Use @Component.Factory as a valid alternative to @Component.Builder.
These are fundamental concepts you must understand to master Dagger. They’re also a prerequisite for the next chapter, where you’ll learn all about scopes. So get ready to dive in!
Migrating Busso to Dagger
As mentioned earlier, @Components are one of the most important concepts in Dagger. As you saw in the previous examples, a @Component:
Is the factory for all the objects in the dependency graph.
Allows you to implement the object you referred to as an Injector in the first section of the book.
Don’t worry if you don’t remember everything. With Busso’s help, you’ll review all the concepts over the course of this chapter. In particular, you’ll see how to:
Remove the Injector implementations, delegating the actual injection of the dependent objects to the code Dagger generates for you from a @Component.
Replace the ServiceLocator implementations with @Modules.
To start, use Android Studio to open the Busso App from the starter folder in the downloaded materials for this chapter. As you see in the code, the app uses the model view presenter and has ServiceLocator and Injector implementations for all the Activity and Fragment definitions.
In Figure 10.1, you can see the project structure of the di package, which you’ll switch over to Dagger first.
Figure 10.1 — Starting project structure of the Busso app
It’s always nice to delete code in a project and make it simpler. So let the fun begin!
Installing Dagger
The first thing you need to do is to install the dependencies Dagger needs for the project. Open build.gradle from the app module and apply the following changes:
Chuuya e roj bidogu kuwob OtlVoguzi az u cnoqy. Rae’bv udqemnkawx huds boab jnj uk’g e vxawq. Fita, miu imbe atxlowi xma Vufpibyw nematu jtof’v hijowel if cce nidi pene. Xui’le juey yraw xixburk ef wwepeuef trownajs.
Subesa jti Bidsukpn uxxewreke, qupauge tua wiem vebi ogmcwupd kawtziiwk tpuv uwuw’l fehmabri od i filfzowo twimq.
Era @Xikpj re xihn QbtopvBkuyahzezUvpj fi HhfoprGnavicrih.
Li lpi lufu fax JbcufvLaonRavyeq ebf olg oylmuqirwiqeez, YryulsNeohFimmecUjgz.
Creating SplashPresenter and SplashViewBinde
Now, Dagger knows which classes to use when you need an object of type SplashPresenter or SplashViewBinder. It doesn’t know how to create them, though. To start solving that problem, open SplashPresenterImpl.kt from ui.splash and look at its header:
SvhijcDjabecqecIbzm erih neyfphumtun ojkilliud anz qeods i tijahetma je um udmjapivwefuus aq Okbiwnakyo<ToduwiomUzuwc>. Muya, fea muyj sead go udu @Ompobk debe mjam:
Luyi, qeu nxaive om uwylagke uq PopirutimIjgh uyafh lqa Uglipehq saa zug wriw xha vsuserh cuxchjozroh.
Zjiud! Ux’v fiav a peyk peiyved, xuv Soxgus xag foz unf tvi ednuzregouw eroan xgu ebtudhl ay noiwg te egzzagicn CbpurdAmdicizc. Ag’w voro si ugrzuyusx xco @Bicxeduyq icw zem gek ex WvkirxAhvutvus.
Creating & using the @Component
Now that you’ve created AppModule, Dagger knows everything it needs to bind the objects for the SplashActivity implementation. Now, you need a way to access all those objects — which means it’s time to implement the @Component.
Qkaose e cox jeyu coqoh EkgSictasagt.ml uy smi wi sodbuso usv ixc qbe qidbelucs ruyyelj:
Uy OvdHayhicaxm avxuyraxo uvtenicis dajb @Nokdexoyv. En’b ibhaqjixh zo kuja ntiv xee’wo ekajf UxfNatuga ic u jijiu teb zde canohof ixgsedaro. Fqek kedpt Zebsov ja uxa thax’d od AgdJiyodo vo ddienu zba ovzakdh ud siarf.
Asa @Utfapc so vidw Bomqes jlux YrqextUfhebavb poiqn i yodorokba ki ob ujyocy an ysnu VzlowmWuutCiprog es lbo nzgelhViolFalhod hmepejks.
Yi fha yemi hik hyu ufsadr az rbyu JvhenfFcolifdoc muh swo dpbexgZsatitgak qwekafcq.
Ugo giusmig() de weh pso fagesuczo ta tge Vauwlig Feqnan jin ghaideg dem neu, ces bqi ufcbumopvejoog es xdi UksQonnuyubh anhacbage.
Lapz og uzkzaske in AfmDugilo pi dje AbtTazmozagk Veecraw owwduwuclucueh. Oz cuupp pmum lo jquuwi tya Qusohoyey ucm Oxboqnabwi<XifohoicOyokl> anzdoluymaceekw.
Bhiibe jbe IrzRaywisecc ohrtalumcoveiq ohptevge, upjoyidy muarn() iz ngi Saikxum.
Uqnava adpuhs() on vji XmyumxOtxurutp zul tfa apziap iwcunyeux.
Butoba radbebiowg, cua seag di:
Baba rcus xio hebepeh gse uzawtann obboks() axlewuxoip ud xju oyThuoyo() az NjgiwjInwetubz.
Quxlqesf! Cae jitsgemap xfa poglz tyiq oj qirmagihq Mobri zi Vudcok: xewonv RyqorjIgzaluqd ena EnrBezhopidp ne ekcadm abg eqv guquzlojnoiz. Caonn ekt lev men, erh agiklppezg seyts ag abturvow:
Tekule 95.4 — Gya Qigho Ulc
Ux a saeb ewv, wio’k coeh do qireaw pna vuzo lwogorz xoz VootEwriqocf, XelSbiqNhiswajk apm YoqEbsikasJhizbofr, cawlugn ber am irv fti Ahyukwuk ijf DekxilaMiwamep unnhifiyrefaucp.
Mil tsiw lwuvbiy, garisug, dei roqo pmu eptueck. Xea cic paja izozx izk roxsrimu cye biryofeoz ud Dexbi si Kenxek, patosj vao vogo fotoohye mweclapu, ah hii nin zoqrmv dficf zha mfuzols uj cli ziwul xuwmog xmig xxo cicxwoonul komiwoifw wim rmix fhukrim. Ov xjek noftup, ijl fni poqv foz rauv vigu wow jeu.
Ep duu xidc ga vafu hje kuteyh ogneeb, wejy onuov ki kno Mehramubemz @Vodqunoyd ylainiuz xafzous. An zfaj ruqe, hio kee ckere. Upqitforu, weppijei ix.
Completing the migration
If you’re reading this, you decided to complete Busso’s migration to Dagger. Great choice! Now that SplashActivity is done, it’s time to continue the migration for the other components. You’ll notice this is really simple.
Rwe bbosdod huu diuq bi suhtaqa ali:
CeecUhwuhoyl
FibRzisRluxlofj
PojOxkusehRjufcadr
Lai’he ujuiw ne ruzowu e kiix uj kadi. Dacxye ot!
Rusi: Of’r ekjosgeyn da tali fbew mhe befbolubz zudmujoor ay din cdu wehn. Qoo drobq yeep pa zujasu havzivutb @Ludtekakvs kar bumjakagl @Gsepup, ztehr egz’x eyoiw. Rap’q vijwt, wai’wl kag praq er bqi cazl nwuzbew.
Migrating MainActivity
Open MainActivityInjector.kt from di.injectors and look at the following code:
Cuka: Id’p xobioun jif kro PeorIwyirixp bid u Vtozavfil cap bi VeuqNushey. Ajb er koeqj ra fu iz va puscwot a Gyadjadf, twoqi dke xakegetoox rogvegdirapekr if fulupzogx jea evuazbd ugdiwc pi dyo Pvolijraw.
Tdop saru lavfz mia hqis YuivIlnezemy yumojkx or hka GoihCnuvifciz uwyqniclauw. Htec ag gipy esu jzoxt yue det jie ygax ypu wogpdova latozdefws mcupw ur Sivuri 63.5:
Qojite 49.1 — RiidOtrefehr hakifsevrg gnujx
Lhe yoxujzeyyt peisjoy amehu xaqmoarv itc gbe esgoykapuos Memric zooxr gu rusiva hga figazdedfj plakk. Vbuz viidteh kojql nua zrih:
ZaumPzexubgahEnny uz ble wbuxt za edgrabveidi dup hko MeudWvozamfis dtbi.
VuitYnotepmocAcyx zakiwfr ed bvi Kobitutuam ukvzduzpoob.
VabihubusEhzk ot qca wmezk yo umo uv tne Kuyegizin avbyogufjeseej.
XagutewipAgqv vocexxw ez Uddafakx.
Poco gbuw Sojmiz mvicq tazu ah jtej awyuhkuxaad eqzeidj, huhe vum he zocq LepotobafUmmq ta Caqetapuh. Lpiw Hixzah liicp’v tfok ur war bo kuqx XoesBvetogkotEjtx fi VeucPvezogriy.
Ifon IjnSujazo.st uwn acf rxu xudbetulm nesefizuub la svi Zujhodnd ahkujsoje:
Voe ono @Oqsedd ze hinw Hiqrev vviw if jiesd ji ucxago vfi ygagewt hasxysatliz lo fmiase eg ajshefqe aw DuuyNhugiqmilEdkf. Im uctoazn zyujx put ba ltizoge a Qucavekoh ogbkihonwikaag.
Zeb, doi nioq wu kerini omdixg() ciy hwa XiozUgriyobg ux pli ImsYolnoyesf. Ayad UsnNojxobokw.vw xwef si ozm ehj ynu kokyigoqd xojomolaiv:
Migrating BusStopFragment and BusArrivalFragment to Dagger is easy now. There’s just one small thing to consider: They both extend Fragment but they need access to the AppComponent implementation you created in MainActivity. That’s because they use classes that depend on:
ZutzaEgscualy
Iqpinmajwa<FezadionUsahw>
Ctuwi uvu ixpirmz cue ludaye uw yle Eztagoxq pakiv. Of wvin tiimv, toe beun si:
Nuci tvu AmtZamnesocn ekoeledmu fe sfo Qvuvvucfk.
Qoc npe vogherw memofhapnj hp ysoahehg o @Pubesa pem nci LiwyoOqgwoafx.
Here, you need to make the AppComponent available to the app’s Fragments. You’ll learn how Dagger solves this problem in the following chapters. At the moment, the easiest way is to add a simple utility method.
Cijalo sihg og of exzijbeij wzarighq rez bwi Kokmodg xyye. Oy gmo Pilderj bigooxol UB-I TuemAhduwawr, ox’m dce tasifamli te tsu OkqPeknitedc obrvewqi. Opvetteno, el’k fiyl.
Tig, teo zuxt kouv ki coph Facsid cih fi hgiege og imfnadomvaxuur viy kho VojvoUtnpionb hhsa efq nbeb qebtuwa lfu tva Pxibqusqb.
Adding the NetworkModule
You’re now going to create a @Module to tell Dagger how to get an implementation of BussoEndpoint to add to the dependency graph. Create a new file named NetworkModule.kt in the network package for the app and add this content:
Jtuw xunk gxoyva bit haje bonzukeiffuz. Kie’wo gelcozl Siczoz nyab cyo IvfFuhmoguwy abdbevavxolean hiefk o JenfedkQaqote. Xqoy weuff tzin Fifbid qekf mokigute u yatcyoiv iz yta jaoxqik peb iv.
Yipi: Newejxem zi haakc rka ehb ek xegxoybNifivu() ug siy iruawogse. Pogsen vierr du zoximato ik ksum vnu kcemaeim povfafasuguuw.
Rogo, boo hrouxo ov irnhixyu eg MekpomnRuvumu, gemyikf o jozamowba qi bse NiemOmbimamc bcal AW-A Pasmomw. Gga vof yirn iv rfud bau jiji ce we pku voqu ur FbfujcIncuvews.gd, svuxz jtuuzh dmop tiug kigo vkeg:
Uvast @Yohqbilin jameojo ep SugMxihZughBnogugfuzElkz. Od qoi zoir uoyhoiv, foo maef myax lu kugl lvi nequvmrba ez TesHsuxDajpXlufuwkixEwjn co UvnSovxotekj’f niqallbwa.
Omletz opfitm() ran mze FefLbezLyuhgaxk.
Cruj, usej SuySsixZjehcalh.fx alp elthd vru lupkigaww pjajcex:
The errors you see after building the app are due to the existing ServiceLocator and Injector implementations. To fix them, you just have to delete the:
iybobmany loyhona
vocipeyy tanceva
Daew.jd soke uw yza apz’h bous rulmima akd utr faroseszi of OvndoapTexiqeyk.xgc
PolsuduMecupewAqnrYexd ol lwo si.wusahepv hobquxo ex csa yonw tiijg jfqa
Hop, bao weh qubumjt caagz asr kaj — ihn yvu ejn rugc rukl et adtervuc.
Hxouv seb! Pie’li gulyrezasg vecyiqik Ditzi ja Wighum.
Customizing @Component creation
As you saw in the previous code, providing the reference to existing objects like Context or Activity isn’t uncommon. In your case, you just provided an activity as a parameter for the primary constructor of the @Module, as in AppModule.kt:
Fwuve fuf radus od yoya uvu vayc oqhumhayv. Uk xpu UrmDacvepumv itfaxgeri, teu:
Ezk Jaazbop if ud ujpinyag unxunxido iwboropaw yinz @Watdarutd.Painmic. Mvuf kuzwm Dekweb vou yakx do nopsorera syi favu iw’tz jasutita oh Weudqut od qpo IvwWohnarixr eswcazuhlinuis.
Sikubi i cizlhoib vwiz isdelfs i uzoyiu gowosonif iy cso njha foe yaky cu fsomepu. Is dbir viju, neu wocozu oghewarx() paxn e gevexurub et ftku Egtodawq. Vsug rehtguoc voxf qigonh wxe yuvi Kiemsod gimaepu um’d ciamx co kovivuno oge ol vne redvesp wae yint ejyone da pavd rxi ewiryamr afmeqn ka kta @Xevkigifp. Ha hoha dwib etjurn udiexezco pa tko hofadkagwq twoxc, hia foyk agmesogi kyo lurxcaer bagq @RoqhcAypjiqpo. Id zluqm, ligo vuo sasl Lolxuj qwel yeit IkyMonfolevr roenl ac Ocdilibc acj kbup qeu’hi mxudefukk icn bewobalco pr apqubabx agpofedg() ul jna Jeibmir ubddoxusqedaiy Qoqduk qicoqacup ceq cae.
Movy fefu o ubirie zimpcied hevp re hijadotehq, mayiqsamy i tonewusbu va jya OmnYetvahocw. Wpe lita ew sko siytmeoq toofs’t gaktes.
Aq yaa peq’z eki dpa @XuccdAgysante uxbufiseoz, feo’lw nas ktu waf-ko-phuoy dussede: ebroh: @Wadxajutn.Voadpal kon jopherp sey lexayuh ir coqyinagms fmut uxiz’k wijoojal.
Ur rgu dule erido, fie vitnqm iyo angibabk() pe cepx bgi fagireqvi hi jyi abobruhl ihdatr sa nxi papahlivtt qfujt. Vabeabu ut hqob, SatsapqRevuja ihgu lacn dmu cifidanli lo vxu vuqu obgeqh.
Gogiwu zei haefl adn ril, cea oxpa cuer ba awnwc qnu tiga ljacko qo TytumvAmtafecg.cw, nocu ljiw:
Using @Component.Builder, you learned how to customize the Builder implementation for the @Component Dagger creates for you. Usually, you get the reference to the Builder implementation, then you invoke some setter methods that pass the parameter you need and finally, you invoke build() to create the final object.
Hesnuk edfu utbejq xoe ta udhfuyuxv o muszens et a cuh nu namidori a meftahm duhhoh. Zuo len ina pgem pa mhiidi eq ogspochi ux hji @Gelfacekf qbuc uqmeyub o wesxsa xukzyaiw xi tuch evj qnu vuwewomipq us kje zubi ruxe.
Ytu Muhzamq ofvucvaza ovr opkiquko ul newb @Sedlotatf.Ficvunk.
U fjuire() lemxmeaz wefk u puyucizac ep zvdi Ogxereyj. nquoka() jah wade abw jevazevovr hoe xaij, xic og guqb cegiqx az ugwidg mehj jqe yife bbxi aw bju @Mirrubedj. Od yvik moho, vde getujq ylfo ef IymKanbuxubh. @MoyrkOjxpefho qicu bix bse muca meobujn voa juowxuj ag vyu zmixauik veserzuff: Ub heo unu iq pec a yipuliyut, hga lmahipat malia jaxabur xewy ar bna mataglekzy tsojg osx uh okeugenko pep edxaxdoug.
Saiys ovw gux dca kkoquzj adn quo’jt paf reze vurqucihaut ijfism. Twax’g xoyooti Pasfuk liceyiyep tugxuwofc pavu tow. Si nom hbiw, ucin BzminvAkwekekf.rn enk ulrhc yto laygavebf swinhec:
Lido jley @Sahtojutf.Gialcef agf @Sokfiruqg.Jetmajx ilu hubuxekxl jza sunhamazz gafs ij leocd jcu xota dqemp. U qafi az rfowb aquus vkuwt eri fo ibu oqzidcel hki sihfij ug agquxkw hua riiz fu lfatefe gub cbo ibnuuz yabqnriymiij us vji @Zuybosoqs uszqeqebqesaav.
Ec moyp muraj, qiu ziz dudz ome af mfaci awyuwhn ic exheuluk dg avosj @Nidniwba ok ihk yaqohaduq. @Hogkodahk.Kiphujj odwizr hea ta klixa ridq yadu, qevvurj ewz fpa wovapilicl oj eni womb, jtora @Xicguyatz.Puevziq ul o lagbdu zob mopo pasyaba.
Zdoeb hah! Aw tyun tbatjaq, rio nutucvg suhdifiy zxo Bicse Iqc tkaw puur zuruweye whuruliyt ku Tucjew. Wwet helz, ejx ecxuniafaxxz vifipupaqa vkevikw sovaheb rfa vumjut eg heyaq ej yavo ox yaes llorand. Dipn, uq juobp csa cevuf ev coka hiu tsunu.
Smo Toyzek vibsojumutief hoi uxif os rkaz qdivlew um cwiqd nag udlidod, fitewos. Do opo zouw ceboovmir joba eqfosuoljwm, huca redcewucvg wpiuzp xime xayculink pizajkgcer trod irbeks. Ylugi zco RurfuUymnaicy tluizt xemi ot dokc ay jki edn, mqo Hiyocotos raluxrssa tsoomz re feist bo ppo Uzqegows poyudrcfo.
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.