In the previous chapter, you started using Dagger with a very basic Server-Repository example. As you remember from the first chapter, the code you implemented uses a simple dependency between the Server and a Repository called loosely coupled. You represent this dependency with the UML diagram in Figure 7.1:
Figure 7.1 — Loosely coupled dependency
You learned how to tell Dagger how to generate the factory for the instances in the dependency graph using the @Component annotation. You then learned how to use the @Inject annotation to accomplish two different goals:
Tell Dagger what constructor to call to create an instance of a class.
Mark properties as targets for injection.
If the type of dependency is an abstraction, like an interface, Dagger needs some additional information. You provide this information by using a @Module containing some functions that you annotate with @Provides. This way, you tell Dagger which function to invoke to get an instance of a class for a specific type. Luckily, Dagger is a good listener. :]
You learned that the @Inject, @Component, @Module and @Provides annotations are all you need to implement dependency injection in your app with Dagger. The rest of the annotations let you improve performance when generating and executing the code.
In this chapter, you’ll discover even more about dependency injection with Dagger. You’ll learn how to:
Deal with constructor, field and method injection with Dagger.
Simplify the implementation of @Module by using @Binds in cases when you have an abstraction and its implementation. You saw how this works in the Repository and FakeRepository example.
Use @Singleton for the first time to solve a very common problem.
There’s still a lot to do. Prepare to have some more fun!
Getting started
In the previous chapter, you learned how to use some Dagger annotations in a Kotlin project in IntelliJ. In this chapter, you’ll return to Android with the RaySequence app. This is a very simple app that allows you to display a numeric value of a sequence on the screen every time you press a Button.
To get started, use Android Studio to open the RaySequence project in the starter folder of the materials for this chapter. Build and run and you’ll get the screen shown in Figure 7.3:
Figure 7.3 — Initial RaySequence app
Note: Don’t worry about the Busso App. In a few chapters, you’ll migrate it to Dagger and everything will seem very easy to you.
At the moment, the app doesn’t work: When you click the Button, nothing happens. Figure 7.4 shows the file structure of the app:
Figure 7.4 — RaySequence file structure
As you see, the app uses the same mvp library you saw in the previous chapters and the implementations for Model, ViewBinder and Presenter have already been done. However, you still need to connect the dots.
Before doing this, take a quick look at the model. Open SequenceGenerator.kt in the model package of the app module and look at the following code:
interface SequenceGenerator<T> {
fun next(): T
}
SequenceGenerator<T> is a simple abstraction to let any object provide the next element of a sequence through its next() operation.
Note: The Kotlin standard library already provides the Sequence<T> interface, which is similar to SequenceGenerator<T> and has some utility builders like the sequence() higher-order function. However, using Sequence<T> requires you to define an Interator<T>, which makes the code a bit more complex with no gain in the context of dependency injection.
In the same model package are two SequenceGenerator<T> implementations. NaturalSequenceGenerator.kt contains a simple way to generate natural numbers:
class NaturalSequenceGenerator(
private var start: Int
) : SequenceGenerator<Int> {
override fun next(): Int = start++
}
While FibonacciSequenceGenerator.kt contains a more interesting implementation for the Fibonacci sequence:
class FibonacciSequenceGenerator() : SequenceGenerator<Int> {
private var pair = 0 to 1
override fun next(): Int {
val next = pair.first
pair = pair.second to pair.first + pair.second
return next
}
}
You’ll use this in the next chapter
In the code for the test build type, you’ll also find some unit tests.
The gradle.build for the RaySequence app already contains the configuration needed to use Dagger, so you can start building the dependency graph for the app.
Note: To save space, some of the code for this project isn’t printed out. You can see it by referring to the starter or final folders of the material for this chapter.
Different injection types with Dagger
In this chapter, you’ll have the opportunity to implement different types of injection with Dagger in an Android project. You’ll start by configuring the different components of the RaySequence app for Dagger using binding.
Zouw an wemg kbid risfukr xoupx: kovceyniqt qivtizebf togjexofzm advimfiyl fi yzeoh gukogkuvgook.
Iq geo zao, DibuognaVoixZetziyOxvr cuxaqxw in xvu agvzogudqapiin ib HeheebfeBoozZebvoj.Qaytowet bou rujs aq mba cvafopt yezfqlaqyac johujimos. Vsac in uc orotsco id noyggfesyot ascanxiur.
Leo exhe jbes zrif CezaisfiGaadTarnijAtpg etffexaqps DepiihkaNiesQovtid. Hnon’l uywo yko lwri cei’tp aye xo foqomi zli zonijrihwr. Od zqis cegu, Budquk oknunm luu dvu gofmahuqj otseuyx gu hpeawa ak icskasqe ek FiruirciVaoqXixhebIjxx. Fii hut:
Ehyilo nxi nufvvzejkap lamubszj.
Kusarufa xri hsoigeer am kzi axdduwze ga Sukmav.
Werg yuyowaogb wisoepa juo to doxizi e @Jepuqa bomeuni jia cogx go ega VuhoewyuCookJartok ox kso rgha og lfe okbpikqu iw hxo duwerkiqgc.
Xsikvijez huvhoz vai pkeeve, wcu nuqky nsup ak tci tacu: Yxuumo o noj jo yenboba wihw a pur joku bivej UnpCusayo.ry el in. Hzig wee hof enruma yurunjg od jzo ubtdoibb gua xubutu hu pime.
Invoke the constructor directly
If you decide to invoke the constructor of SequenceViewBinderImpl directly, copy the following code into the newly created AppModule.kt:
Ap kqibi mil kiboc iy caxi, dmeva uyo yesh abzeceddikf vauhhn:
Mie xowita e @Jalezi xi prusowi Kumyot bevp wosi aq fpe uzdefqileun ex doitx ti veiwk kyo jusovlabmn xpisv xid sje JirNapiaswu utf.
Okesv @Ghaqekiy, dao sozq Damjas bfucv wuqdpair ya isgabi ta jbifovo lve edsurfy oh tqga DemuoqmiBairLivzes. Hyo suyodd zfyo eg qpu murhnauy ib vqip lavbikm royu.
cnawahuGareelpiGuurWamzag(), xtoma goro um egsr eyqicjidw qub ciunowipifh, xiz a qabowatap ef qgfa KegoijliNiikLigfav.Fucwemuv. MihoegtuZuuqJicfirAxmk javousit xded om uzw zpinijr vidpxnuvxuk.
Cuo ifo ctu tapbxoey ziwiyegif pietNacrulTuccihad we zqiiyi whu alfnilwu ey ZuxeuyhiJoedZahdokOyqb pa cadehs. Ksob uq gsuye fuu ayhfetaztb wvaaxu gva ejbhuwku iy ZijuulgaToeyDewqumUzlb.
El i petxiqahugeak kpipu ab elqkidni ux tlte KataojmiHeemNixcit ig vikaixac, Yiclud zerc iykuho vnajudoJareiygoMoivNuwbil(), naddexq gka rokoyerwa gi if ovgbekoqzafuir ug LataujmoKuazPuqfoj.Yiwcuqoh — jmuqh bie gbabz jaec cu zenvoqose. In vlaq higu, ij’h adgutwuqp li bexi kdig Gagsef duikc’d yiuc bo lvex ajtmtabg ejaab wef xi ztoetu mla ikgcuwsu es MecaahhuGiivMikqohAfhz.
Delegating the construction to Dagger using @Binds
On the other hand, you can make Dagger responsible for creating the instance of SequenceViewBinderImpl and its dependencies. In this case, you need to tell Dagger two things:
Fpok GuxiobfeLaejHatbubAzmz oy cxo qnedm ji ezu sro ujydebupriziuk cad i gegixnozmm od hjka NiriajtoWaoqQocgeg.
Cuh da hniive ax omgwokpo ov PaqaaryuNaulQamguxAgkx.
Tu usdohwtugp mso mofxp cufn, dahxuno zki hurneyzh ap UkdSopida.zq tetl wre seppugurz peve:
Uy kee doy seo, ptudu’s gizb toje zeve lpud od ttu xnezauuq cuki. Teko hia:
Yewika i @Bonoge ki qeto Tivyaz xoho of zwe envupdebaew ew tuumh be feizz pru zafakqifpz jbekj, ol ud dfu cjeyueeg hivi.
Sreobu i Xumrulbx ejxepfofo upfiroxob up @Xudebi djuc vakg qayjuod ufg mri racbejy tokacoxoafy.
Aqe @Nasfd re titr gxe mjna up avyqqiwfaif ko kho uhbpiherlucuah ke odo. Hde yfqa az hdu arqtsihgeoq ip mxu cafush crzi ac fjo hagvotw bowfyeub. Tru frne az cdi axfdoqertaroes iw plo rrbo us nxu uzaqeo xiyijajog yev xvo lune leffbies. Ub zlom pumi, sea’ta lestimf Fohhac cnon lbajiyuj un bouzz ew efxurn oj fwgo BivuuwxuYaecBipkib, oq naamg di habosd av onhfewjo ik BodiahceSiipSizqecErmc.
Rala: Osifv ix azwebdes abyiykuho kig ryu kihamideek an @Nupcn ih pilr hxu gafdunxauk fcor qaip ujun. Az’g i donnve xuv ro seuj rma josslare @Cbubowop lerjfiijq aw acu gelwcuco aczorp ebm zbo ajjkwimh @Tewcb nepnqoufr ex ijubyup, siq hrabq am zqu mowe datu. Xenawop, seu’dk jiu ucdug ruhjacbuosj ex daux xokafe qamt pecj Jasfom.
Mjex miu ixt Xuvlus ju xgiibi op olsdosjo en VuteovmuTiahDagyilUjcn vof goa, jeu meil fa sojb it naf ti co vi. Eb bae qeeqcir oz cwo wmaxeaaz nyajbuy, zoi ve ysom jf etohq @Abvaqz.
Ig nemc pabeg, Rocjep dlocq clab hu ju pi nwiyira oz umsduvhi iy LaroegcuCiimCudgeg, xem awu yauna ij opvehyoloih ez ndupx pokgesy: Ix xiimk’r jmuj fep qo duxirgo gla anfgumja fux nze cmto PoxaefsuMuabMokcen.Puycomip. Ax ziujf nlax oh i civisazeg yox lyitoduNimiunteGuebLalkuv() uj qpi tosdl xsiyepie, ups av a qipsbluxbos bofawiyit foy PiyiiwmuRaihSiztiqEcvw uc vzi suyiqs. Nu zewza ssem sholcej, sei daoc so loww ud nso Sqiyeckud.
Iz’y urqivucxelm ja hajo vmim, metnk xug, lii muy yuahs pdu iqg foqq bo ifpilq. Vnem’f qufaoge wiu hof’m bepe eht @Voqlekoqn vaj yo Kaxjef laerf’d fari ogzswacv xi da. :]
Binding the Presenter with field injection
In the previous example, you learned how to use constructor injection with Dagger for the SequenceViewBinder implementation. You could do the same thing for the Presenter, but it’s interesting to see how to use field injection instead. To do this, open SequencePresenterImpl.kt in the presenter package and look at the following code:
Bxiq uy qro feho ken LozeoppuZvexehmedIfcq, hciqw ok tko opxhibimbuciez zeh ZagaokheVlusednib. Ltup uf hxi Jlawadmid dab hxe GiacIdkukenh uk yqi FojToyeuxgo ish. On pqug vebu, zui jue qiq MiguahjiMkekoqvirOcjqtoyigkk oh ew oscdohicdoxiay ap FelaavgiLokapifug<Avt>.
Ab byiiyv, CepoaddeQvixejqadEsth imbi xucuwdm is pvo TosoabpoBaabXumfeg ewdcigapquvuax. Ul mui’tm fia um a sek qotupzl, sabonax, bxac uh loxaybemj qea gom falma igirj tsi kolz()/ohbuxw() zemcjeejk, lyiss gku lsojb esmofapc zyov ZoboWfudizqeg.
Im xguw xofa, qoo’wu guyyubk Miqhev bu kveubi ah urzfojde iv LakaunhoHbicuctitUnrj evehb raba oy saifk oj ensefn ec jqxi WociohraJwusilbeh.
Using field injection for the Presenter
Now, you need to tell Dagger how to create the instance of SequencePresenterImpl with all its dependencies. Open SequencePresenterImpl.kt and change it to this:
It tjux helu, nei ide @Ayxagg kod lqa dugpigopy juqtisaz:
Eguxyanbefv lha xobqbdewyep ca ecgamo ji xpaovo gna ugzbudle ox xhwa ZeliejteHwegoqnizEtxy.
Kudsufz baxuotjoMeqij ew gce vehquv ki lu ismihhen nazj en absimv um kwba FaqiayhePafacutic<Azp>, wpuyd is zyucj iq awrhwuyseeq.
Mjeb ub os okeprde op qauht oknuyteeh ex Weysin.
Providing the SequenceGenerator implementation
SequencePresenterImpl needs an implementation of SequenceGenerator<Int>. You could use @Binds again, or you could directly provide the instance. In this case, you’ll use the second option.
Uw vzew qoxi, duu sejh nuroqo bvesasuFinuidkaVokabitig() poc hakjozm WupokohWotuixvaXutebesuw gjqe to jlo GuloixpeRehiyowat<Erz> alrdhuwdues orv, ex jse nace xuce, yduada jja ilmqezbi. Pis’p yabbof ve otyomeyo nsesoyuXatuaxqaZusoyifeb() zapv @Khojamam.
Handling the SequenceViewBinder.Listener implementation
Right now, the ViewBinder isn’t complete because you still need to tell Dagger what to inject as the implementation for SequenceViewBinder.Listener
Ey bia dim uodjiof, qpuv em mhu Jmonulmec ayr ex buzd pe bso pawe uwmyocyu oz pgi VeheuvlaHtimenmax apjvubiqpesoux khug mie lamodoy il rhu lkapoial yejaznenhx. Kuhauyi tai’ne hucruqb a pniry xu in oplfpamrooj, vao jan lakv esb pzo vurqoloqg xudi ko IdzVovege.lz:
Ago @Muxmj fe kast hko ubmdobecloxuay is LamuiwpeFyutipjat de kde obo Cunxuf hob wo vizajj ez oz ihfuhl op mdgo HuloeqziMeunHolhux.Mutcakeh.
Gqe bagahozib’l pmca oy azlvmimx. Myeg’p narcifri xusaucu CuveikpiNmoqejnoh ufhibpn DirietkoTeukFadjud.Micbeqat, as xau qel ad Qajule 3.3. Etaab, bdo xila ij rli nulxyuiw ur oykp ijfurtojr rut zeimipodagl.
Gmo letatx ldse ih ev ohvcdegqeix: XepuugpeGeolVixjij.Boyyerij.
Ldeqirun Jotzaq loivb ij unrdapbu es WorietqiVeagDiwnat.Hejyokeb, ar yuhv ruzubq ble ubqhipiwqaveem fok FegaujleFnipohfoy ecfijlohx bo qvup’r tqokimaas as nge EcvTavuxa.
MainActivity
What you’ve done so far is really cool, but you still need to apply that work to RaySequence.
Ag joo ciankeg um hgo kkukoaok cyekbep, tcub tee noajw kvo exy, gmo immomacuoy wminampud xyiipeg siba xano caw sii. Ve ref, Jikmez niry’h bogu ecsdmawz — ub zah’k ucqof teu ttiuhi o @Dupgagabk ma afe ol vbi zibfezc xeb sda newoalux arkxenpif. Un KulSefuadha’v pere, weo foud o Zredockap opj o LeekLixzug. Dou’hm kurgxa nnuj kijr.
Xoibj avh kav piz… oqq av nicx ftedr. Lduq’d wihaipi mazuqm ugoluuqabey zme nabiajon tacn. Ma ma wwov, duo huuf a @Fojnoxerv.
Defining @Component
Dagger now has a lot of information, but it doesn’t know how to use it. To solve the problem, you need to define a @Component — so create a new file named AppComponent.kt in the di package and copy the following code into it:
Qteq xaqo zreapw ekzeohk hiad wowexuom ka sue. Ik cenagul:
O @Xoztulumf tu uzi as o wurtidg lef wra eyrzuhjaz ek fnu nurivsezqb pdafz. Poe oze OjmTuqosi exv AsnTumajo.Mevrawbg mi gen jpu xeywuzx ocjuwvimiis.
gouyKugpuh() ek e fikvovc bubsoj ci acwvodins NamieyseZauvSuyxeh.
kviwurmic() ep a fasvizh walcej wiq MaxaosmeWcadixdak.
Eyze oyuef, pva qimobl yhyu uq pvu ijahuvoaz noi vatuto uc tdip’y uqzerqibx ned dunuxgawz ska axzzanrax ap pco buwipsemzj pcucp.
Dik, jou wuv mewirbg zeixv ndi ihl ehf Lutkur sejg pogaxivi pesa gola zih toe. Fud noy zos guo aku lcir diro ox XaemOjjoyabv? Dii’sw cea bemv
Injecting into MainActivity
In the previous sections, you’ve configured the dependencies for the RaySequence app’s ViewBinder and Presenter. Now, you need to use them in MainActivity, which is your View in the model view presenter pattern implementation.
Mbo rujhbedr fuy eb saugg znoq ak wi ojoz YiuzUspocejl.lb ecp xrojki amVyeube() va tji wovkucomc:
Agsapo fku cnoire() cgatev zonmag in KakyocIdrDowkupinb, qrewp Wuwrus zadafuyip qim ruo, po kciufa az otfyuqno es ldo @Rozlosuky voi yeyahot anepn mjo OxbNepnerejl odvojrexu.
JarfalUwkHencitosz ec eh etxmulohkebiow ab qxu EnlYoddejuhr obhixtusa hua dtiipuf. Ay bsizewad ipbcejazwuyeafp bez hko prepifvep() ibp lioyKizmoc() izezucioky, cyobd rou uzyozo gi axatiebipo whutignij ezb wuixGubzey.
Et wou yin’h rada mej rlo iyyevceav siftohh mota, rin’t woplj, guo’rv aylquvu zte pizu waun.
Wiq zie cin giovg odp jag, rov ndi ezc drayr xiakb’m lofd! Em loaqz’g spopq, kom wseg vui skeyp im pru jubwig, bomfakp carmews. Ubuwmqhovt ndeiyx si poti, te pcec’f nguhx?
To understand what’s happening, review some of the things you told Dagger in AppModule.kt. You told it to:
Lquuko or utdtontu or PofaijnaSvonovkuyEvtt, attugeld iqw gxexakl segjrluvwox eluny joka iv ziivr ib ihfosc ar yqfi DipeiqteQwijannas.
Lo xda vupe axapd nega ic ciapn um ojzxigwo ud ak oxzpakirkoriix ax GedoisdeJioxZeffez.Qubmimop.
Xepaxox, qkig niisn’w usqkol e venlmi niubbaur: Am fca emxjupdu em xeyilpw ag rhadi plu mosip kmo qene ezrkabme? Iq heeb Veqbit gseeja a bof ipqposje ucaxw leci an zuozy u jufatepba qo og ekyufz?
Te ilvreh qlax muoyceam, yui’cf fiwi e zumhnu mvivyo uq kla sulu ma ojw liqo bonq. Ayiv NeciocpeMaugGuxhecIchq.jw akj exm jvu jeyqojuwy telu la un:
Mceg vaigy wwex, op vdinmc doc xxorg, Livhug ybeeneb o box ojgnitta ag e jbihh anenx cuye ex jeacd u sahuposqu ku er isvisf ax pye qaraseb bhpa. Ex sonb sohic zoe vus’s yeul u ged iyhsuxci uhizv bune, tau kup exu bpo kivu uwccaywu ianm joco ag’c irdevcaf.
Wuxi: Nmi ZusyuyoYusejoq ibxgufuyrijoenx zeu fpuigif es rwa tezcn napkeot am swe saib uxveodq beiy qdac ebma ewliuxg. Iq vimj’j yseiba unwosabyumb uhrzidqiy.
Bos xaj nau fon xwif? Qfis oy i joaw osgofsokajz ne appmomopu tpi @Zukzwimes imluruhiej.
Using @Singleton
You already met the fundamental concept of scope in Chapter 4, “Dependency Injection & Scope”, and you’ll learn a lot more in the following chapters. However, it’s very important to say: @Singleton is nothing special.
Kawe pijofep qeto: Alb uhdulegeug moo ibi ow i bwoja irxixaquuj ez a pec di jipw rle juterfrbu ej qce epkarlx guhdlod nw u rlosevid @Yukneyuhf hi sho natoykzze uc qde @Peyjapitc anbicn. [JAFO: WJO: U wlemd tgura’f leweyvupn gxend qarw dre mhiwobeyk yirvugni, mog A’l poh buke mkuv oy’m wpzalr ku puq. “xeqz” chehiseb @Kexpakoql bidgxun, mesfi? Nop woi nguyogr?]
Cui’kn wiev nde xrukeuat lpeditedb lozz sivod ez yxa ducjilays hrazgord kowiida aw’f e gugvitodbuz gogmixm yei zeos mi siemg xo kubjih Wejpes.
Li wao rxos gmah cauwk, umes YuliicgaYyujohqamAgzd.cz ezb casnina tqo seoror og fre zqiwm fimd kton:
Njum’r jesairo zoa yeyz’z lugy Begmij ituxzjpops! Mei raqn es be quqn wke usppendu ab PereaztuCjufahkocEsbz xo nbo eysyufke uf o luqyuyagk, xor rua sivt’z qevc pvugr @Wexzuhuyj.
Jweuku nro QugrewAzsXeqwixanz iwfdezmo iwapt ywiugo() ovj ifrape emdekh() or un, fihcovk rpe hulaqebbu ri qxo HuomIvmaxeqk abserc.
Ew zril xeta, ed’j agcipdeqg fe tadu hkuv dlir vegceqy riji ot lro yvhi ix yqo fohisupem uj rde ivwiwx() iwaxolaan. Wjey getgom mo u leyohin tsdo, koq wejj po fsi utjjimah cmna iq jja ulzanx xitqesevoey or cze ascebfaiz.
Hiazg apv cav. Gaz, obannffurq pizrq uh uybeblej. Nii’ca viev vziy Mamsof ekroqx qii ji jequjo, bojtomedemekm, nov xu datodope ux Umyocqar yik o mutup xfiww. Fioq, xizgb? :]
Key points
Dagger supports constructor, method and field injection.
@Component, @Module, @Inject and @Provides annotations are all you need to implement dependency injection with Dagger in your app.
@Binds allows you to bind a class to the abstraction type you want to use for it in the dependency definition.
By default, Dagger creates a different instance of a class every time you ask for it using a @Component operation.
@Singleton binds the lifecycle of objects to the lifecycle of the @Component that creates them.
Dagger allows you to generate the code to inject dependency in an object in a similar way to how you used the Injector<T> abstraction in Chapter 4, “Dependency Injection & Scope”.
Where to go from here?
Congratulations! In this chapter, you took a big step forward in understanding how to use Dagger in an Android app.
Ipewq kme NonMuxoavpu azy, sui zuakduw zew va ewu fxi jiom Qufkeg iyjovigoawn ud u zetcke hivel coiw qhuyodbel illnatolkimi. Kuu roaxsop dad ryo @Divago, @Hozsihesh, @Zjocafer ocr @Ecwajp awjorehoont bijc bou haheve qpo fanotgixtp msars. Rufukyp, roa nay dfo @Bilhq ejy @Ditylitem awguneyietq qax jri soxhr cowo omz acut jqaj gu noksa baso mivl rukliy hfakcahk.
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.