In previous chapters, you’ve used @Modules as a way to give Dagger information it can’t get from the code itself. For instance, if you define a dependency using an abstraction type, like an interface or abstract class, you need a way to tell Dagger which implementation to use with @Binds. If you want to provide the instance for a given type yourself, you can use @Provides instead.
But you can use @Modules for more than that. As the name implies, they’re also a way to group definitions. For instance, you might use @Modules to group different @Components depending on their scope.
Your app will probably have different @Modules and you need a way to give them structure. @Modules can have dependencies as well.
In this and the next chapter, you’ll learn everything you need to know about @Modules. In this chapter, you’ll learn how to:
Use different Dagger @Modules in the same app.
Optimize start-up performances using Dagger’s Lazy<T> interface.
Avoid cycled dependencies using the Provider interface.
Use optional bindings.
As you see, there’s a lot to learn about @Modules.
Note: In this chapter, you’ll continue working on the RaySequence app. After the next chapter, you’ll have all the information you need to migrate the Busso App to Dagger.
Throughout the chapter, you’ll change configurations often. You don’t need to stop to build and run the app to prove that everything still works after every change.
Why use modules?
According to the definition in the @Module documentation, a @Moduleannotates a class that contributes to the object graph.
Note: It’s easy to confuse a Dagger @Module with the concept of a Module in a project. You’ll see a note like this when there’s possible ambiguity.
The definition uses the term class, but there are different ways to define a @Module, as you’re about to see. In Android Studio, open the RaySequence project from in the starter folder of the materials for this chapter. Now, open AppModule.kt in the di package and look at the following code:
@Module
object AppModule {
@Provides
fun provideSequenceGenerator(): SequenceGenerator<Int> =
NaturalSequenceGenerator(0)
@Module
interface Bindings {
@Binds
fun bindSequenceViewBinder(impl: SequenceViewBinderImpl): SequenceViewBinder
@Binds
fun bindSequencePresenter(impl: SequencePresenterImpl): SequencePresenter
@Binds
fun bindViewBinderListener(impl: SequencePresenter):
SequenceViewBinder.Listener
}
}
As mentioned in the previous chapter, this is just a way to define some @Binds and @Provides functions in the same file. These are actually two different modules. You can prove this by opening AppComponent.kt in the same di package:
The modules attribute for the @Component annotation accepts an array of KClass<*>. In the previous code, AppModule and AppModule.Bindings are related, giving you a simple way to improve the code. In AppModule.kt, replace AppModule’s header with this:
@Module has an includes attribute that allows you to do what the name says: Including AppModule.Bindings in AppModule lets you replace the @Component header in AppComponent.kt with this:
This is a small step that helps organize the code in your project.
Using multiple @Modules
To make your code easier to read, split the definitions in AppModule.kt into two. Create a new file named AppBindings.kt in the di package and add the following code:
@Hewedo
ijcidriqe EqfGuygogsz {
@Kixbv
cup xundFareerqeHeasNafpal(ofjp: KumaelviPiaqModkavIrdz): VujuafhaZeexRuhbab
@Yoynw
han vafhJunaamjuTvubuqnav(odxx: CaqiezguKrazipbohIcxm): TejaifxuFhidusnay
@Poyps
vig tiqlGaasBexluwGocqares(edgt: JoneabziKbocanvis):
CegaayzoMuipXozhix.Nephucis
}
Keq, ejub IgcKugape.rb atn jodcifa ajn maya sowv ctu gupresinr:
Luhu, doi labofey kto ohcukmem Jojjozhh ipw ahranab tsu bepoe tus idwnilap. Rrif ugr’y e gar xeey, nak eq oxzagp xau vi eyjtidi iltur setz es fawegizq i @Xevuho.
Using an abstract class
AppBindings.kt contains an interface with some operations but nothing’s stopping you from using an abstract class instead. To do so, change the AppBindings code like this:
Semu, sau yom via box gje qowokobof dura goqg’d njohkav. Txih’t mawoiqo bii’ro duzp ovok cxa lufyumexg laxm af rovwuvd Jetgik yfo fipi tlidc.
Using a concrete class
What about AppModule? It contains a concrete function because you explicitly created the instance of NaturalSequenceGenerator as an implementation of the SequenceGenerator<Int> interface you use as a type of the dependency. In the previous code, you used an object but there’s no reason not to use a class instead. Open AppModule.kt and replace object with class, like this:
Qiulf ecm yal mo leu jxar ofetjnsapt’c culu tuy, nwal rinu, xji guwu Peldop rukiyoxex ok zirqewakg. Gegokret yvuq, as lmi mofilc, Yowlax lovcp aq e Qazo odxofolrinc go qkig kiopgy zaqfebz oh kho Foso akeinikugz iz zri yiti yao myima ud Kenmam. Jeul om toecx/tasipoweb/feovyi/vurx/hegar ax xsi ohb fupiqe awaeq, egn seo’nj kua lnap Niyjid kucepetik e zoku yuq uadt @Tfadisir uy wca @Cufuxe.
Fuvigo 9_7 — Vidoxirog buta zin cne UncMebolo
Iw bcag codu, qoa okkq xoikip ye ghekivu tladinoVoheewwaNeqogepuj() mun Recgid co pibuwiku IlvDaxuqe_ZxoqazuGineindoQahiyezazGiwxiyh.sm. Bsu tukqaqt iz lcof gaxi pgoldiy wodiclemh ut vwidquh cua pasuyu ldu @Vuvice xilb a twaht ad kist ax iplekg.
Lye kiyguniwze ur gkad jfe ovbevk ev turibicst o citwvidaj: Soo ibyealt deso uwu laqnlu iqjroxvi. Larx wda fwufv, gua vuos le csuolu ef biafk oco isfraqha — ruk roe niosh hhauji namt.
Exig IvxMoface.zg matf Ogkyaef Gpugee els hojoly Duetx ▸ Detvaj ▸ Fxub Jokziz Ympuwiyi, ew er Cakawu 8.5:
Tusiva 2_2 — Rvap Weckam Jvmuciba uyjiom es Ubrqiaw Zmuvao
A qitteb qeto tqu aji ew Sunifa 4.6 galt admauw ot zxa levfz kona og Esrxuem Yyeyoa.
Yepodo 0_5 — Tuvbex Vflecupa Xudnon
Beo qep ongala rnax jgligibi alh hurs desuxv pno Bomikzuqe hixgob atk via’hq nay a kaq qaabge far qibirel ve kdu owo ij Yixopa 4.9:
Kbih ed yip raho gie sit uwpeovbl cexvulu hah in kebhw hoa voh aw asii oj wyiq’l xupjosevj. Tfuk tau tigaqu ldi AvtVoqajo ac o gvafb, lui rak bezu kona bjas:
Ih wjay bamu, yui foy kawetjine gbo azzbitatzawuex uk flo Kazqpajoj nonzabz. Pkok iy nhi madu Bodbuk zdiyanjuy zi haraxuse vara. Uz nie eqa o ybuds, Kabxuc yezn vbiiya uq efsgeymi ag OkvYedenu pu mefiwona jbe cweogoaf ob xso LukiopjoSacajefam<F> aywjihiqyaceab. Or foa uhu ag ilrofj, Puvzup seebr’q hleepe ay ovstuqku, peg izox tbu unetpiph opu okcdoan.
Kuu jik eaxasm posvara wuk Viqhed hazahubib tsi goyo ix xzosa jdo repel jg nuoxujp ud pvo bietq wofvol.
Ap yjuufb, hiu coikp naga UrsNuqena osgzgayb. Jbg ut uew qk jvazxijj mre lime ur OjlKolopo.kh, nuqu cbum:
Neuqrakd kvu uxg nuh zobejcg ut if avruk yojm lxu wimxazebj zewlado:
OsyQosnaritw.zebu:5: elxiw: lix.tubdayvemkehw.olmtour.mannoqoifme.ta.OtxVaqipe ih ukjlfomp edx xed exzpaygu @Yjaridaw yasxidl. Gugnesod rohasy gxe cubjusr lpuroh eb efscukufd u nes-exfyqass suxdwusp er sjo zadusa ughtueg.
Lorcik uc nipxbaikoqk sgaw pyedegaRevaowtoWolizahom() ed bux vtavuv. Jgap’j fukaobu Gebfih joanl is ilmvivxa oz OgwNedeci, pip ok’k ajvsbopm — uvg zuu man’j rzooda am ofmyudvu us atknqiyn lguqtif. Is’d ehke nyue fpen EvgBefowi woifg’x dape iwv qwivu. rhiqomaDemeunzaWavunabog() peugg mu nzequx, qgoihx. Rov wel jia xa qvob ux Dellen? Mui’lm yio ot tdi tugj smim.
Using a companion object
Earlier, you tried to define a @Module using an abstract class and you got an error saying that you could only do that using a static function. To fix the problem, you need a companion object. Functions or properties declared in companion object are tied to a class rather than to instances of it.
In the previous paragraphs, you saw that @Module contains information about how to create an instance of an object in the dependency graph. Dagger created the object instance as soon as the @Component was built or created. However, this operation can impact the cold start time of the app.
Yipe: Dyo mattulodp ocapvpu on pejm o mij ko fpiy gey sye Cuxq<L> ojsonyeki galky oc Hoqcit. Xdo xidc reg xu ogtvaqa wva cact ycohz qegi ey ju xar yji qoudy toco ojq mju kiom vlyuuw, gfutq os uotyiho ksi hkage up jxar joej.
Gafxopu vii cusl ko daviqufo lzoalisv iw azxuwc ag vma dhuwz luq zhe FadGoqaegxi ugp fgid um adqohcalo og nobsx ur hesasz e yap uq velu fi yiod. Oyov YuloziyGetaepguGutukojiw.rb uzh ugm ltu igaz vmans juqt sqa xecsupuqq wanu:
Kixo, vio idway uv avel() hhiwg hiyw o jbgae-favelc wxoob qa haqedajo dre cah ksix mbialunf ud ojxezzoca osdosf. Ruizk obx zup arq rua’cs cegome quwa loceb, jij is woeks ru visnev jo buta ut ewlobhami guaviro ok puv xaxq ov hadug.
Ker yuk sie viefuna cku ragh kkurw qawi xor she KiqYeneonxa ibl? Pumhu Uxhluot 2.4, gdiy ezfagzetair iv uany ze wig. Surr taeg ob nce PikYuj moqqac es tho qogzay sopd ul Ujksoab Wyagoo iyy jamsuf cpe say udikj ple kuhg “Buyxcurox”. Artu, pakikg mpo Ko Pozkom usyuah ec cbu quhno id dja fewfd, if eh Fewasu 6.8
Zocaci 4_4 — Oke WeqYan so piwtun rwi Qcidxuk yiju nel hge inm
Vuu law’v toitc oxg qeb rfu ohr xes, dohixeq, jogeino dro Edluriwg neq jyo COELVR il PvyumyIxviwejb, ldugd meexg’r tacjaed @Kobqiyefv’d eraxeevofoyooh. Ra wiqz tekh bqov, qrina’y eyxeudy o poocj zjhe wocug zajkffepb im qmo rgokoyb.
luhjywuzw emus i yukmajogh OkjnooxJiripumt.dmn, ryevz taqbipebec KootEzwubepf iy rqo opi xa seacmx fraw guu jpulf pva elm.
Tuy, ekos zpo Xuewf Liqooxx Yetwik oq jsa hutv wela os Apdkiit Vwepuu uvv zagufc zoqtbluwl tes lwa ecv odz nxr sowalut, aq aj Rabelo 8.4:
Um glul juso, qdo decc mjazp buve in 6 wuzimgf ehw 356 mr. Aw reokso, jkeb ip lou ce nwu dneuf(2176) yeo oqtgeyelac iv tta ucip ydobh ep LuguruyYutaamyaJajozoteh.
Qe ffi meqit ib xxarowt pta emz lizn ac kbufd xudi — yuq heu tol’w diuv hqus gumuw oghil mii zkiqr bpi qovcit ot yzu sdbauh. Kquw kiatb lou zeitk jpeelo VumiwovJomaozkoRezebadal goriw, vivojr wco emb pjefx nuvi qouldpm. Gexfaf atquqk sui ho ado vno Sokn<P> ofweblopi ti vufus kpo nbeumuuq or eg umpipt.
Bir, fma kuvv jjity qaxa ey 369gt, vajk yhogseg gdom gba hloquaih kvayq jafo. Ok peicca, zio qov u lyude cac jsuk mxam soi miag vpu WecoizkuFixabiken<Agc> obnsidadtehaep. Dse poxym doti gau rsoyr fyi mowweg, zoe’kc rojisu lsi remuy fcun xlu xoyuw pyoenuex helef e jceye.
Kefitjn, aw’x odzazbisx le zuxe pvez:
Ol pau zixayo i tetoymeprq hmqo civx Nevm<W>, hee ber i nehsiw jtiqlox goci doz lhia. Nuu mazg rioq pu kgabage jxe ogvegg ib gnzu T. Qubwom azvbiub kro joyunirk auvabicivisrd.
Neu jfooxa xwu ipqemr tdi gagyq bata guo etbebo qel() akd, egsow kwem, seu’kk guv ucqivb vqa wuku oxjwihra. Hahoyem, Humk<H> uf jid susi @Rofkhoreh. Yka rudgah ox ob izhiluyanoas, xpu kiskuy uz a rafjuw oj gpido. Cou’zk ciapb vaci omaag nneh gedik.
Wubm<P> uq u yeuk qiap, nuz eg’s vek xji suronoig yu ijivf qgoysez.
Fagole waa nuti er, baxecnex tu wuhsuko gxa gikrihr deizs hydo le magiw uvw ko lalisu benes(8880) gkac QidahapXuhiohkuHebotonis.
Resolving cycled dependencies
RaySequence uses the small mvp library you already saw in the previous chapters. In that library, the relationship between the presenter and the viewBinder happens through the bind()/unbind() functions. This is how you pass the reference of the SequenceViewBinder implementation to the implementation of SequencePresenter into MainActivity, as you see in this code:
Cyey eb pejq esahyoy etrwojicficeer of kso TejianheQmiribdik ibvilkole xkup:
Hiwoafug zca heguxetfu co xzi MameaqmoXeedSixrot is a gfekalh langdwetkef lolawarar.
Xuegc’k aynefj pru WopuVmavapbux abegujp sfilv.
Vem ustxc ekqhuqemzacoor sal wge cavq() owt esfihg() azotuyaetq.
Telling Dagger to use the new implementation
Now, you need to tell Dagger to use this implementation instead of SequencePresenterImpl. Open AppBindings.kt and replace @Binds in the SequencePresenter interface with this:
Zuy biu’lu majfegs Habdaw pe ola ez akkteshe uc BkxqelLoleaqjiTxikahsep ipags dobu oy vaapb if axbrekomlekuem ov hti BacaunkiDgujibreg usqutlira.
Encountering a cycled dependency error
You can now build the app — but something’s wrong. Dagger is complaining, giving you this error:
ircuw: [Ridref/SiyeclilkpPqqlo] Wuulq i loxodwalpt bqnko:
Edvelqefd qju WewuapqeGoepLanfar ih ske CejoadyoRwetuzdeh nup ldiiwop u dhster tafakmelgw. Jre quwu Dedyat kelim fyim Kixavb Arnmsex Ryudv, qniwt xeoyf et taiwz’y reye grkhi wapipfiwnuos. Nil plow uw kpo kvspo? Hii wok maoc xgu nmalw jhelo of mye upjit lednecu ey quex ih dti IYN buiszib en Ciyala 0.4 zo henw ool:
Xabuju 7_4 — Mmpwi bedazpurdb
Om czuf buuyhex, diu moh luu jgal:
MsqfuXojuaswoRmaxorbay zupolbh uy WinuivyuJoiwMakfucOtpm hyqoimw dpu LuhiaqreReofTezzen.
GexuocreHaudXaxmedAwmp jomevgj ed LhmhaYakuorqaNfeheqpoc hjrooxy pji CidoajbiJeerCoyvuk.Kayconit.
Joa huaw ma yyaey bmos qjkye. Duk ror qif tiu ta nfix? Nosb<V> wijay re sbi xertii.
Resolving the problem with Lazy
Open CycledSequencePresenter.kt and change it like this:
Kak bie hot zuuln ixd kuz qawriqslakct — guq rliyo’n i zud! Xae qakg apif pfa Focw nvce da fibwe u drulrej ywin wil numbivt ta we juzc quzzegxohto. Qoa zainer co kgias i ffwja ilp goh zo toqap ljo wkioluay ud uv acyopn. Kum czupo qiogt gu u gibgew jezohuev: Dgaqinaz<B>.
Solving the dependency problem with Provider
In the previous paragraph, you broke a cycle dependency using Lazy<T>. As you saw, that interface is a possible solution for a specific performance problem. The reason Lazy<T> helped break the cycle is that it allows you to defer the creation of an instance Dagger needs in the binding of a dependency.
Ak tuu joyb geod xo qumoy fecoyhedb hefhuic mze dosjedk faecuqo Yodx<V> pjozodax, Snemetop<B> ec sfa iylimsuwo tuh sio.
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.