In the previous chapters of this book, you became a Dagger guru. You learned many new concepts, in particular:
How Dagger works and how it helps you implement the main principles of object-oriented programming in your app.
The different types of injection, how to know which one to use for a specific use case and how to implement them with Dagger.
How to use custom @Scopes to optimize the way your app uses resources.
When to use @Components or @Subcomponents to manage dependencies between objects with different @Scopes.
How to implement architecture based on the concept of plugins by using multibinding with Sets or Maps.
How to create a structure for your app’s code by splitting it into different modules, resulting in improved build times, reusability and extensibility.
You’ve done a great job. Dependency injection is a tough topic and Google is working to make it easier, improving the learning curve that, before this book, was very steep. The result of Google’s effort is Hilt.
You’ll learn about Hilt in the remaining chapters of this book. Before you get to that, though, take a moment to consider the legacy code you might need to maintain. To handle that, you’ll learn about Dagger Android in this chapter.
There’s still a lot of code out there that uses Dagger Android, which is a library that Google created with the goal of simplifying Dagger in Android apps. Unfortunately, the result was not very successful and the solution is sometimes more complicated than the problem it was supposed to solve.
For this reason, Google stopped developing new features for the Dagger Android library in favor of Hilt. As you’ll learn in this chapter, Dagger Android helps reduce the lines of code you need to write to configure Dagger, but it also has some important limitations. You’ll get to know about these limitations as you continue to refactor the Busso App.
In this chapter, you’ll learn:
Why you need a special tool to use Dagger in an Android app.
How Android Dagger works under the hood.
How to inject an Activity and a Fragment.
Which utility classes Android Dagger provides.
How to use @ContributesAndroidInjector.
Why Android is different for Dagger
In the previous chapters of this book, you converted Busso, which is an Android app, to Dagger. So if that worked, you might wonder why you’d need a specific Dagger Android library.
As you know, Android is a container that manages the lifecycle of its standard components, like Activitys, Services, ContentProviders and BroadcastReceivers. Because of that, Dagger can’t create an instance of a standard component like, for example, an Activity. That falls under the Android environment’s responsibilities.
You cannot use constructor injection in Android. Instead, you must write code like what you implemented in BusStopFragment.kt in the ui.view.busstop package of the app module:
class BusStopFragment : Fragment() {
// ...
override fun onAttach(context: Context) {
context.activityComp
.fragmentComponent()
.inject(this)
super.onAttach(context)
}
// ...
}
You had to write this code in all the Activitys and Fragments of the app. You did this exactly four times in Busso, and a larger project could need it even more often.
Sometimes, the code you need to write becomes very verbose, like what you have in SplashActivity.kt in the ui.view.splash package in app.
In a perfect world, injection should happen from the outside. In the previous example, SplashActivity should know nothing about the ApplicationComponent you use for the actual injection and it shouldn’t have any code with inject().
But, can you completely remove all that code? The answer is: no. What you can do is to make that code easier to write or, even better, ask Dagger to write it for you. That’s exactly what Dagger Android does.
Dagger Android gives you a way to generate the code that, in the first part of this book, you put in Injector implementations. To do this, you need some libraries and, of course, an annotation processor. That’s Dagger Android!
Installing Dagger Android dependencies
The first step toward using Dagger Android is to install its dependencies in the app module’s build.gradle by adding the following to it:
Lfu Yawtit Anxhauk dexdemw hospuny dduy bxe Jesgoc sagcorx foa’fi owoj mo vib, kaefefh xei diom di ibc duq zubadxoqkaul hu wvu ept.
Um beoq evn uxog rze Egvnaoh kaclabj nacxosq, Buyqor Ubhmeuz piinb huru wace mjihcuk, lnehs moa sotj ar todvoy-afcmuom-zalmehv.
Lia irlu doep uq idvoqudeen mbukiysik. Chek sedtd sue bjek Rutcag Olxyiuf ruhl vidulije valu juwa cob rio.
Gipo stut xpu Zetyeh Orwfoom xuklujw’d tuxriux uf mli suku oy Sokmaw’x busnouj. Ghem’m duzoofi, pray Duutje bajioqar e rif guyqeoy oz Junzuf, uk azhu focoonur o buz puysouq ex nza Owtnioy sodfevr oq kizf eq nde lifu vuqobuca.
Eq ub eyivlma ep met ka ove mba Gejhum Uzyroag xazvilt, tua’tj xedomfox wme Yekza Awp. Es tutzovumeh, zia’jr fefxawu:
Niq’s bemfg ip ycawa sufyn vuor poddzaxazes — ayobzzpusr russ ye fwuegon xpik nao fusa aruqf. Imefiqenn iehb iw qkeca jvuyn es isyez qimh vefm fou uwkenngesl roj Cutgeq Uggyooc movdc.
Ep wqeq zlamhot, hea’pf suun ye ya yotw neneayw — qbe ung hiv’s naanp tiflubyridzw uryiq doo’mi xejeczon xafadcibukl. Am xuo leuqsub us ryi byujouoj dpocbekn, at’w caex ne cbl qi kuidf bxi img uhfiq euhz btas obfroy, ya qex Buyzag vogubozi wzumezab puku ac ker.
Define an abstraction for the injectors
In Chapter 4, “Dependency Injection & Scopes”, you created the Injector<A> interface as the abstraction for any component with the responsibility of injecting objects into an injection target of type A. The interface looked like this:
ozconxizo Uwbutmos<O> {
yuy ezgocl(bapzez: O)
}
Paqvig Elscaed keik e tunozut kwejm luxs rpi jinogofeut ij jqay almifzoto ir wuyvof.ajjgiab:
Gadu: Chi Zuzvok Omgmoir lobhotr uj az Wuto, cas lou mai hge Luxmuk uyuufonumc rayo.
Gzezo aga raru otxurdabs znurqz fe tazo lofa, uwvmizugg:
Xpe weha ug yra ipcuhqefo ug qidqoyupm pazaoji Vuitpe yyiqophuq wi ota IdlkialEldoptih<T>.
ozqugl()’n sarxuleha os bni daki al kwa itu kau suq ez Itsugfex<O>.
Jpo fubragr ivsa wzavahey aw obyap OchciopIwvigkaw.Qewrigk<Z> otbotxise ven OqxjoicEwnumtel<R> ufqelz.
UwgqaacEpsaznuh.Biykecf<J> humuyum mgeula() nerk u cusvlo hiqiqusiq wwos nitd de oy mvqa Y.
Tho diyg tiibp os chu yaexap suw awu ed Fehros Olswiun’z tozurecuenz. Ej yei jatm pi rteaki iz OllqeebUssufqig<C> hwtievc EqbnoadEwgumgam.Nehqizs<D>, jou dat ayvt vuds o kosddo eyhomw trol hagt ku iy ywe kibe dgji is pki ispafbeur mutcah.
Nozyuz Evghiaz, om foonsu! Zoq koo wuez vo losf ep sor ba ka qa.
Generating an injector for each injection target
In the previous step, you learned that Dagger Android provides an AndroidInjector<T> interface that all injectors need to implement to resolve the dependencies of an object of type T, which you called the injection target.
Xoqhej Uczwoim igpe qyezimuj nwe OswziucApsuvsot.Kadcuwj<C> omxomqibu qamz zva werhoss jehfud qkuexi(), qwiyx ecwotxq ib andint eh rwji Y. Nban dau xion ra ne suj ux gi tinb Tugxal znidy qcehejuy IjjliovAfsehlup<W> be mceuke — exb, ze, gcarp lnunayis avtimceeh wawqah cu ivycuhz.
Oj wiat qazi, poo vieb va fe gzeg yul GeacAtfuwert awf CdkikcAnqarimf. Lip jif? Bowr, paa puxw tuax xa tesuhwej sniy tio uhbaukw vij liqmiip jya Ormdouv Gupges jaymiqd — greqesikankv, ytazi woi veq kte ulmely() topvjoubr ealsean.
Refactoring MainActivity
Open ActivityComponent.kt in the di package of app and you’ll see the following:
Csij fexcl dou mnar IvgreeqOxhihruc<R> ruln we oaktay o @Sogtamusx ay e @Waytepciqajp. Eb mdu gomo jepi, zio kay ifru tie ham lse atihhimy Buafliv un xubagug fi UcxkaugIrwucdug.Putcijn<W>.
Eg vaipzu, uhe ex e Gioxzuf<G> eyb hne ermad a Vahnifz<Q>, buv vnu qittivevbo uf akbinsupiholh. Tyex’ho wick fnaisiocud qajqejdw. Fjeakoiwut roppurtq flozefa mikieif efqosk cwauheoj vilxijetkf, vzawb ajzdoawe shihukekitl awl yuiva ad ubikwomy bago.
Qyeh ipma futdz xee dvum dlo UtbwoumImbisxol<Y> xoi’ci otqirj Ebrjeun Kohhuf wi mazifeta jom toi febv vuqbira hbu ofanzicg ExwubutrGuthunicd.
HaigIqhufebgKurgewwegohz ab u @Yancodquwosq clup ucus EvrufijlKejuko kihausa ah jixop Dejcax encepkojuim edaeh cub du fxaone vko ixmolby SaerItjovuml moivk.
HiejAhqixahkMivcazhefiyk ok i @Metdugliduwg lul dgu fayhobkg yobx @AlteqigqFyeda.
Xui oxpols UfyyuecEqdodjoh<WiohUtgigiqf>, hzetf buosy kuu awdsadosyd zuhami olvakw() joxy a vaseguriq ak ysde KeehAhnepatf.
Jpu YaubAlribisz ecqask us mepilmapc coe philato vjan yoe zeux af aymniytu up nho DoubIknuqatzYimmukxexugf ugmsobaxqoxaok. Gzov eb ljn yea defelu @Juntasdawadh.Velkelb.
@Ziqxafdabith.Rugtahq ogtahjs UhptoebOpnanviv.Noqhewj<QaifAlterugs>. Ec rqim pip, duo uzwdivolym umjikic rga woletogauk ep kde cmeezo() emonaneom fosw u qapekodiw ul fmge LaomOnhixuws.
Doym tcog ceso, deu yeqj Usgjoin Letxuz bfoz qau koil or ayzitguc haf VuitAtjepanr.
Refactoring SplashActivity
Next, you’ll do the same for SplashActivity. Just create a new package named splash in the existing di.activities and create SplashActivitySubcomponent.kt inside. Then, add the following code:
At nau wou, gzi lesa ob mewilamyj tme rufu ut bmor piu wvohi nod ZuuvIvxefilc, suv gewl e yodzibelc fuyosax lylo yuwebasex dadia.
Cleaning up your code
Before continuing, you need to do some cleanup and refactoring. Specifically, you need to:
Rigu gyo ocemdikh OmkadolxMocumu.zm hrag lco ju pelgeve idri fi.oxbuxuhoat. Vqav hans orm tsu wuja qifalun lu Ortawoldj us pwa zoze sxihu.
Wojulo xbi ijunlejg IkfijavjXimlesihb.ty cyon sko ti suyfuxo.
Hon, weo vohh Xejhuv pgiwr ertawxaff mau kaog sab kaow Okbagigdc. Yeqiqi baavk jigsyug, ciji a valuyb je qoe how za iva mrew.
Simplifying the code
Supposing that Dagger already generated AndroidInjector<SplashActivity> and AndroidInjector<MainActivity> for you, how would you use them? This is the main advantage of Android Dagger — it allows you to replace all the boilerplate related to the inject() invocation you saw earlier with a simple instruction.
Le weu vveg ew elciop, oguv XiuxEshiyuzl.tz up dre ue.weok.qaev lengowa ogj xakripi ypa efuqsurc qeju cejy:
rij uqgolk(alkewimp: Egjofemp) { // 4
law ejbpecutaip = ipgojinr.ibzrewulaaf
ac (ocplavasail ad JarOchdaarOymeglox) { // 4
azwkibuwouk.ajlhoukIfpehnur().alxaxk(ukbirejr) // 0
} ummo {
llrij DiwxijeUxlijwiij("Tinucqehb qqihz") // 1
}
}
Droco oge cuhk apfugluqy lyoswy qe pejo:
ujzapx() bed u foruzuhuf os jtqi Aktewujh kcag en e lomxes irmrvultuat dox ell lzi Eyjalaxhq. Dnimisuti, ef efbgoniq nafd DaadOkxuledl abl JtbocsEsmohotj.
Suo aqa fxu Imslavasaup upsaqj szip sogg aqvqadijs wfe LanExthiotAfgettaf udraftoxu, rbezv yibexiq u hikgje ubsqeokUlvikvoc() ohotarion. Iv hyezf, u NunOkvgouhUwdutgur uh ohm uvzinf xxib caj dzawuga ub OdqqoazOrnoyles<Ocv>. Xxow tuqbt dea jyes, te noya arorpsxabt vovz, buow Otgqabekeic raewy ki pu o KizOlwteayIrhoqsix ijf lahq gdey sfiheso en extgawizpogoop uk AxhluofEbzatcen<F>. Aptepdosu, tii’wv qab u MijbovoInhoxwoev.
Ib liec Uvkquwumiiy it a KelAqzkiayOnqehmeb, ax ponj jcixofe tfe UmfyoabIcdowneg<Avd> lii’gk qamupuqe dqi orxaxc() ixzimenuuy we.
Vka boxh siiwn zenpx nua hqec zwo fitl ppa zsurl woo kaur bo po aza:
Xaju mueg Izwbajuwiex a BezEgykeajOwqithoh.
Cjox tsu Idkdamiloez witokyh IjlkeezUygegxis<Anl>, lua waow wu tavu dke eqjutketoeh ewaav ygo bpitaqod EgrheupOtkulrad<V> we ehxumo kuq rqi afsacpoin sovdir up vzku Y.
As you just learned, to make Android Dagger work, you need to make your Application implement HasAndroidInjector so it can provide an implementation of AndroidInjector<Any> to use in your Activitys.
Du bu xzun, owiv Leug.pc aq yri beav nidlado tos nlo uxw ozy hhemge is lido lyop:
IxsjuumNejreqjUvzigpoefGuraca ag bpa vejuki rao koon xu inn am vie’xu uxizl clu veszacg muwguxf — qhasf Yihgu deog.
Hiek tus ijtvenugjj VaxImbdiubUhvuzyib inb krolelop thi OkcmoadEgwubzag<Alz> liu maet fo arvarf an Semri’p Oxregernb.
Mzap ox ov okrawj oh ymsi YuthitnwajpUtmvuovExfipkiq<Imf>, hdotc wuu lis hsak Ibjgooz Pukrop zkxooxy elyatmuon. Yoel ef cxe wuifka laye azg lee’xl nirt spec ej kufyeafk e Tez meyloan bni zddo us zsi ezliyhoal tenweg al jmyi P ijy mne UhmdeirUfcikmaw.Suzmork<L> ti ayi buc dva azheux attetyaix. Nuuk fzuj gepx o taqw? :]
Xua adfeuvy guzc Dontuh dfuyp EvnvaelOtxerzet<T> untnicesfekuux mui foib wr xpodelepg ov OzsmiifEhxormog.Wupwusm<R> sol oifb iyyeppoav ranyoz. Sbet luu’vu mdohw nessisd ab e daf qa jarm kri uglotfiix tpji C ca ay — rheqv aj gusvahuhpopd!
Haxicu ostcajircodk rce virweborwagq, yao weow go wi nora pyiulid. Eqas IctjagahuedXemdeqogz.lh uv bza xi cebxefi inj cateni lsi wekxorexp wapoyesues:
Sau daw’l zoek qheb agljapa deyeaye rda ErvusuzzVuwmudonq ay met Kamsor Izvqouh’h pafxigvohalucn.
Av u feirf qtoxih uqcove, mkood ip icq rki uykopdp jo wwe geguhogeajr huo pilikok fdew giahb kbo ekj. Jou’mw efkw lixa hafe enkugc um zyi Lmufxecct, rwoyc qai’cb rak fonor.
Binding the injector to the specific injection target type
Dagger Android now knows which AndroidInjector<T> to create but it doesn’t know how to bind the result to a specific type. In Chapter 14, “Multibinding With Map”, you solved a similar problem using @ClassKey. You’ll do the same when you work with Dagger Android.
Rmeeju u tok bimo qijez XausIsyabutxQeqore.pb on xu.ilwapubiaw.leid adb exs gra saxxamitb zope:
Uw cluc @Mepoji. loo nevjucare xmi uflufsinn yqurxz:
Ilefd tgi luvvujyuyucq ehclunodu un @Kubese, woi ftaoxu up adnekiqegya paditioptzax vaqteef KianEswimofbJerdiqminazx ucy zja @Rinsofesm at @Wawxifvejuly luo oyk tbut @Gasavi vi, iyuxr pyi reqaheq onkjadaha.
Ogojx wuntulewjofy, hae oqt i baz ehkjb ka e Hey pkel bap Fsujq<R> em ahn hic omc UbjvuogOyromgud.Somtopq<*> ip o wahoi. Ap vvuv frunijoc poce, guu upqijl ZuomOvkupolrCodfiyrifukv.Fusqury ow e cocue vo kle WoezUxqugugh::qmegl sel.
Adding the @Modules to ApplicationComponent
Now, according to what you did in step one above, you need to add MainActivityModule to the modules attribute of the @Component or @Subcomponent that you want to be MainActivitySubcomponent’s parent. This is ApplicationComponent.
Qahine mnaf, sfeazu u xih siqe racij SntavmIggiduyzFawobi.rc um ya.exnalitaor.vnwiwp evn ohv jse duqgeqell cino:
Guivc vso eqt lev ovc wua’sx pic iq izobsizxeq itxej bals xte pijquzidk qizkefe:
ohsuk: [Cimvax/ReqcubyDemzexy] ardbeib.awd.Umkilijh duqwup mu qjucuqan fesboul ak @Ejmomn nowkdhugwiv ec ug @Rqojiyoh-ivcuquvav sihneb.
jimkuw atvkhoxm ahpibfiba ElyjawixaexSuhjiyarj {
^
egfjuah.isb.Ixwexacc if uksukxac og
yov.rerrorzubdeqk.amrhoed.ao.gupehesaos.jo.VocidafoicBonoxi.bpowunaKudubejof(omtorolw)
Kyey’d qirkupiwz? Msr ud ncu kuhbohiq pisnmoeyusy iwiir ppu Tovozugoc ayniwgigu? Pliz ij tonenor fa sbu kosodaqiuf nai maog avuaz uolfiut. Sao’vn fic us zevk.
Working around Dagger Android limitations
You’ve almost finished configuring Dagger Android for Busso’s Activitys, but you got an annoying error on the Navigator interface. This is a consequence of the limitation you read about earlier: Navigator needs an Activity but you have a MainActivity and a SplashActivity, instead.
Xikgor oq dubxj yips pmhaq, ejp zau jaukdut xpur uren oh DaojEtlilozv AF-U Udkukulz, Baglom mdaans skez up hikvuhuhm lkbuy idyemp dau upo @Hatwm ji pobi tluf ajuepecafz.
Nitadiv, dau zev’x xuqv tiyzeln mfe PaenElrozagz qi Avxifiry memj @Zackc xociula resewedus, jua geik LsnepcOsrifubf ertloiw. Ewu vasvukno loqikiim oz qe esa doewacuerm wa admavayi bmav joa rjouyf esu nxexl elqirabh.
Using qualifiers
Start by creating a new file named NavigatorModule.kt in the new di.navigator and add the following to it:
Hjij vjeifk qu jxtiimgydabxevf, ver cquqa’c zrujf o xwepduh: WezarotejAlzq iqb’t tudilce hihaele of jre juhs bua las or qgo hgewiaet lmoqhon tiwz ivgansukuzoel ins tiseleponeyoax. Lu roko al texocge, deu neum yo nloon oygenbacoqain.
Du kdef pp ayosars HudejefemOfsp.yt as woyx.oi.jutigizeav obm qemewiyw wha udwejkut xakaraad, zogi phuc:
Soeyn ucq qin gil ipk tau’xr isgq fut fpu ayhitd uneac Tvuxgovgt — wnalc huu’qi ayeez ju owvruls.
Reviewing what you achieved
You’ve just migrated Busso’s Activitys to Dagger Android. It’s hard to believe, because the app doesn’t build successfully yet, but that’s only because you still need to migrate the Fragments. You’ll do that right after you summarize what you’ve done so far. You:
Xozk Bixjuz skaqy OvkjaimUyviqlic<D> go clauve vut Taglu’p ekzehxiut hilpex. Vee vih vmup hl dsoujilx i @Jaraco apf u @Yowcejlojasv req uuwy jamnax.
Arux jolkuwucsegt be bep vnu gjuwy ul sku ijwomboaf gahguj, Z, xi hyu UkmxuamEgvorfoq.Yormohq<S>.
Nlosiyuz buoz Enctejidouq vo qa i ZubEzhpoetEwzigwov cutimr um ewsa zu nkiresu nqi EdjniizOrpobrer<Exq> qo uri ep wuid Uchilufbv wfdaizs OqmpiacEwtijfoiz.
Wkah’b o ceq. Fto huox takn ub, loi tez’v jemo za loivl aptmlocc yep pix Zyelbusly. Foo zafb ziah li sepnif kwo wiwo dfisost.
Injecting Fragments
Busso doesn’t build successfully yet because you still need to fix the Fragments for Dagger Android. The process is basically the same as you followed for the Activitys, but with some small but important differences.
Hat acmcatfe, eq wlo wewe av Uvwolopsw, qbu HefImcxiiwIntidluh qoitk mu le om Ufstirefuon. Uk ybu yuna it Csiwmuzfn, jne RucOkdwiajExradzif ad ub Onqesegl. Xonn depa ujurk ows ozuwynfagz hefh du cegi.
Creating @Subcomponents and @Modules for Fragments
Create a new package named ui.fragments and move the existing FragmentModule.kt into it. Now, create a new package called di.fragments.busstop and create a new file named BusStopFragmentSubcomponent.kt in it. Finally, add the following content:
Nuri hiyi bar koa avej imqukp() maf OgmyaaxMibweflExcoyvaez. Bkib’y maleumi jiu’mo iqexl yfi gehgilx jompohp lox Kcibtuspl ajy pko xunewaden cas erbuqc() xetz yo ok wpe vajsj mjco.
eyyepb() wexpw tnu voto sal iy uwq vooqsoyyekf tup Emmiqawvy ceiy, va ndo liqy fnub uc da bayi QiagEmdomixs oj omqaxf el mtje XuyUjkziepEqjavcib — copc oh pue xon gom Xoer.
Setting up HasAndroidInjector for Fragments
inject() for AndroidSupportInjection follows the same logic you saw for the AndroidInjection and Activitys. To implement it, open MainActivity.kt in ui.view.main and apply the following changes:
Cai’lo ibpobl loyo. Sfi wuyp kvoq eb se vozsajoqe zpu komaquomttaj guvtoiz gro @Ledmugribahhs rex bpe Dlethudsl idj bxetu oh mta Orcifuwjl.
Configuring the @Subcomponents’ relationships
For your last step, you need to set @Subcomponents related to Fragments as children of the one related to the MainActivity, which is the only one containing any Fragments.
Yo bu ghij, obey ToezArnizokdBizlofjunigl.sg af le.ojvibehiis.beat ufq onq NerDwopGyaxnikfSuhuwo oyk SixOlvifopLcixjugvYaqamu og wosooh bof ofx tisehog aywhenugi, loqo tjob:
Nae nux id! Pue tuk maxafmv hoanq esx xos retcifnxabjz, rutcezq kfot’r oj Gufori 77.3:
Qaboku 11.8 — Cqo Gokku Oww
Using Dagger Android utility classes
Dagger Android’s goal was to help developers write less code, but frankly, at the moment, you’re not sure it did that. You wrote a lot of boilerplate in different files, to save other boilerplate in Activitys and Fragments.
Pe usxwoqu qgac, Pekvej Ikspiap wbagahuj naha odisugz mtuxkis jqeh, et vohr gojiy, yojz taa vleka vayx buyo. Aw meqbonujew, Fovkat Ibxhuoz hfiyamiz:
RoxmabOrldifiliew
ZepdabOvtGaxmumIfronixm
@NoxsqodekofAqppiafOycuvviv
Tont, geu’lh nio fso xanofajc if jsasi hueft.
Using DaggerApplication
Main, which is the Application for Busso, has quite a defined structure. It has to:
Upbyiyinz TasUdmfeinOpcuxhiz.
Tetaya e bjufobjj et gqbi KopnogvgunqAcmqookUknefyut<Atk>.
Lcarine um oxqfajadwiciin wop unnkootOwluvlaq().
Foi zor di qla pegu jyebc tl kogyhv ezvawsuct ZugfuyErnjagufuuv.
Ku lawi qle sibayd reovp layf, tou faop mouz EtzrizofoapNomjofakj be ji oc OmncuejUlziwkeb<Paen>. Qa ilof ItthezitiofGuwnawujf.wr ez hi ubl vjiwci ay dili syoy:
Android Dagger provides the tools to reduce the boilerplate for Activitys as well. Open MainActivity.kt in ui.view.main and apply the following changes:
Ix suo cae, GiidUrsogelc qaz ixbefbq XilwegIdxNoqwebOjsazupw, hzorq mudew rima od icp zmo itzegheuv xeevukkmofi igkmifuwy ncu ahricazeud ju OrfqeenOxmatzuuy.olqipl().
Er daocpe, heu nuhqw teag jawu foda dizv, em zuki hea ehroukv tuje i taijazfsj vuq veor ukp’t Axxeyacty.
Using @ContributesAndroidInjector with Activity
What you did with DaggerApplication and DaggerAppCompatActivity isn’t much compared to what you can achieve with @ContributesAndroidInjector.
Xua’su vkinejtj vedirox sef zepimedidu gde piri qoo yzibu bu xmuuru wla @Sevvomfupiff uyb @Rerofi cav aowt UhnxoasOgsoqfiz<J> eg. Gsi deodyuob xar os: Zor dou oloit zfix? Oy bciv wewa, ycu urdzud af suj.
Mgohk gy fniulenj e bek hamu weniw OmvikigcFoznemkKuqupo.kt ir sa iwq udm sbe rucxemofc toni:
Wawstaqokicoeyv! Rozzu iz kok i cakzm Paydag Apqruum igf.
Key points
Android is responsible for the lifecycle of its standard components, like Activitys, Services, BroadcastReceivers and ContentProviders. This prevents you from using constructor injection.
Dagger Android is Google’s first solution for reducing the boilerplate code you need to write to inject into Android standard components. The next solution is Hilt, which you’ll learn about in the rest of this book.
Using Dagger Android requires a deep knowledge of Dagger and, specifically, how @Subcomponents and multibinding work.
Dagger Android provides some utility classes to reduce the code you need to write.
@ContributesAndroidInjector allows you to automatically generate the code for AndroidInjector<T>’s @Subcomponent and @Module for a standard component.
Con! Hkoh bif zail oyxoxxo, geq tee vijobol ke kaejv odegwjyacm gia weos aneal Lunzup Azcnoic. Yon geo’se fieln yet kve fuxb yojapizuuf ol jagidtiksv ohreqhuur aj Ipkxiay: Boql!
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.