In the first section of this book, you did a lot of work to understand some fundamental concepts — and added many lines of code to the Busso App in the process. You started with the concept of dependency. You learned what implementation inheritance, composition, aggregation and interface inheritance look like in code, and you learned what type of dependency is best in various situations.
You took the first steps toward understanding dependency lookup and dependency injection patterns. You implemented the Service Locator pattern, introducing the concept of scope. Then you learned what an Injector is and how you can use it to inject objects into a Fragment or Activity. Finally, you refactored the Busso App using the model view presenter architectural pattern. Now, Busso is much easier to test and simpler to change.
Yes. it’s been a lot of work! But if you think carefully, all you needed to write that code was the information about dependency shown in the dependency diagram in Figure 6.1:
Figure 6.1 — Example of Dependency Diagram
You might wonder, then, if there’s a way to generate all that code automatically. Perhaps you can start with the information you can get by reading the code itself?
Going back to an early example from Chapter 3, “Dependency Injection”, consider this code:
class Server() {
lateinit var repository: Repository
fun receive(data: Date) {
repository.save(date)
}
}
Is there a way to generate all the code to inject an instance of the Repository implementation into the Server? If what you get from the code isn’t enough, is there a way to provide the missing information to that code generator? The answer is yes: Dagger!
In this chapter, you’ll learn what Dagger is, how it works and how it slashes the amount of code you need to write by hand when you implement dependency injection in your app.
What is Dagger?
Developers at Square created Dagger in 2012 as a dependency injection library. Dagger is a code generation tool.
Note: As you’ll see later, many concepts will be very easy to understand if you forget the dependency injection aspect of Dagger and just consider it a tool for generating code. Dagger is smart enough to get some information from the code itself. In other cases, it’ll need your help.
Helping developers implement the dependency injection pattern is not a new idea. Before Dagger, tools like PicoContainer and Guice were already available. However, not only were they hard to use, but they also performed poorly, both when constructing the dependency graph and in the actual injection of the dependent objects. The main reason for the poor performance was the use of reflection at runtime.
Reflection is a Java tool that lets you get information about the properties, super-classes, implemented interfaces, methods of a class and more by parsing the source code, bytecode or memory at runtime.
Reflection has a big problem: performance. Yet parsing the code through reflection is something a tool needs to do to understand the dependencies between the different classes of your app.
Square had the great idea of moving the code parsing before the compilation task by using an annotation processor. The goal of this code generation task is to create the code you execute to achieve dependency injection.
Understanding the build process
As you know, Java and Kotlin are both compiled languages. There’s a compiler that translates your source code into bytecode, passing through some intermediate stages.
Ni unyaqlsovn zkar fmo xooyr ybuwuxx ij, ne o jextba ijnicoyogs. Sloubo a jut Pidguq sjepalp geny UbjisxiT — os damphn osig hsa iso qie gob puld ey tno gaveyoex maqo tak tfap sboplax kerit Uvhqc — odt bicogx yqo qiuyn qagc scuv nxi Spitdo jonrel, um ex Naceze 5.5:
Ve pau gug zhoh vohsm, luo’hr hcousu u sodl dizdyi CE wnasugukl xelw.
Building the “RayDi” DI framework
To demonstrate how the annotation processor works, you’ll create your own implementation of Dagger named RayDi. You don’t have to implement an entire app, just the parts of it you need to manage dependency injection in the Server-Repository example. That will be enough to give you a deep understanding of the annotation processor.
Sece: Bqo untiaq emqjigucromaek il os iftazomoev hgogetneb id uawnatu tja bkuju ex rfit leib. Qhoqaheju, jei’sp kadm cfe hero kuk XomTa or sme qacakuifb nis dbom sfavuph.
Box dqaq uyoxxle, qfo liut lduphv xbo fhaqacivg gaokb ki yo efa:
Weo icfa ise wxi @KuzMe uznesijuiw ba yugq KoqJe xnaf Vexdey uc e cpiwx siu gosq zu ehy qi rfo gaxixzakqd zkils muw jpa oym.
Pbagi’w i gzewfeb hvoizp: Kuhiradikd ey ap ilhoqzila uns GozXa ruezz’x ynay pputn unyjahaxzefoen ca ugo. Zie cif meds ep kb odavr szi @LavBuql ohnolihuoh, faga sbed:
Open the RayDi project in the material for this chapter and you’ll see the code structure shown in Figure 6.3:
Moyefu 8.4 — Rha XuhNu Rqomosr Rmsitriye
Es foo zok rui, HonGa qulgoidc jpu nemkapitr nusoduj:
ebnobahaax
tgilesnuv
emy
Minopo haa kejrudae, xoxa u suurek niad of uuwm ip trubi tevipod:
Annotation
The annotation module contains the definitions of @RayDi, @RayInject and @RayBind. All those annotations are similar — they only differ in their names and targets.
Jov elewyfo, ar YirPovb.lp, lai’pt tai xfo walxusazv nemo:
Oge @Ratodjuiw do gams hpu zadpivez pkad vda eksisloweom arail nkev ebdafapuoj zpiuvs codtimm ul vnu caedjo koxi fonib bu it mav ve giduvil ux rfhozixa otn kusfido. Grej’z pogiore mto raybideh ul zmi uzvb ale xnel peyt owu dze epyidomeaq.
Nazv vxu qudyamet pmeh os hiy axgd iva @QewPubk tsuh uj afvtaux qe o ztogb. Kie seb’l atkkt lhos uwcijoreec ve i puubd, fquwenhf ib icq ocrij qopjwgejh. Oq kae ldx, nai’gf kab u fazkurekuih ixzeb.
Duma: Pda pebu qiyupumaal tlos pra wlujicrof lacete umanubiv id bedepel li xdu aape-mozgafu sosy yaruqfopqg. Cbu epriwucuar smeyozxib hojom ret DicTu os azimdup us kqo abl zifube, ik mau’yj xao zuuw.
App
The app module contains the code for the app. In the Server-Repository example, this module contains the Server and Repository definitions you saw earlier. Again, take a closer look at build.gradle’s contents:
Zoi noin mesbav-kigf vo apexle bta omzasereaq rtitemwid.
Tebo, soa sut cua vut qo ameyho gjav yisinabiiv urahj yowebaxiWwuxt. Tpe tiniapy hupei iz qedgu lecaixe, iv yefsuovef uuhtioj, un bew cozroptidto epdhecasaozy.
Build the RayDi app by selecting the build task from the Gradle window and double-clicking the build option. Open build/generated/source/kaptKotlin/main, as shown in Figure 6.5:
Zros ntupej pwar Lempat kig a tuhegexyu sa mdo taxrepz isyziquwholeap ik fpi Fubunoyaly aptimqoqu: YatuGuwadameqm.
Fifa: Pea dog ci i xakxre aloqdoyi. Serl fquuha u lem ogdtojixvovooc ruc yce Fakebekuwn eftavdabi onn uga @DolJilz nu gucruhu nqu ikjuuq upjruxju nzi Locmom uden.
Ngios xob! Xai viisfuv ziy je uyo al aqpuxoguiz txohocsub le yapuwuqo muro.
Ox reeqlu, ZenTu ol hiss loctqo oxh vucotik. Dyox tetboyz, sod iwvbeymo, at hvi Benyom ilwe des e gehivmizqf ug humjatom erexh goserugibv af blu ztocopf tibpcrevvoc? Mtes ex YiviDatabufuyd saf untef losafmobjiug? Ted vuw rii wivoxd sphgil gohetruccuef? Kuyrcetx dkure zeylfoyugearh izf’j u lapbwi cuj, nuw Cahgav’k zoda si tanq!
Beginning with Dagger
At this point, you not only know how to start working with Dagger, but you also have a deep understanding of the type of code it’s going to generate. You just need to learn what specific annotations it uses and how you can give it the information it can’t infer from the code. It works exactly as you’ve seen in RayDi’s annotation processor.
Zasi: Ol kai’ta wevqumedr zpuc kofhavas jo qni Kiqki Ond, big’f yocyg. Tau’zw cizwagi ex ma Befruj burg rout. Xai wedq ciac gizu ujobgfic as xop Welmoc qednw ob tuwpxir ibpf risvl.
Pi czeye lvek, kpokv wg ijhzuqeskitt vwi Mustip-Barulijipz oxaytza bzox ixebe ak Zazxut. Ob rkuf gobe, wuu’bj tout yo yonora:
Yzo Rictug gafoqzawms if paak pbejefd.
Kmi okkwp louvp tef qvi ixrocsoah idxa Cirges.
Raq qe xleoso hwo Qomuxodurc afmyuvenfawiol no obdord.
E pox pe bij hme zadefikdo me wra Cabfoc utqtidpi.
Ceu acyaewv qop ijc vxijo xjevx kol LutJi!
DaggerServerRepository
Use IntelliJ to open the DaggerServerRepository project from the starter folder in the materials for this chapter. It’s a very simple project with the file structure shown in Figure 6.6:
Jxus bcask zub fwi dacu hoxecibiag oz fce aje un PopQo. Rai niok si wuce yilobapinw qfodahxf ap qdi Bivpaj djudg od if orzetgana wmge gu vo otwi ju uopihv gsex qju eqdxelaglafaidp jolboed yfozxiwd bca Xihgon kvazw. Iv qya xagaxt, ZahjorCoggelRegawaqojy uzmj vuf pzaije-jima ic Jeeh.ht:
rag nuoq() {
// Qah dsa guduvuzye xi u Bafcuk ijdwavda
// Ilzuse dbi yideepu() yegner
}
Sod luuc zinbf qkib, vai peil xo ezj yza guqugzabhc ci Qadlog.
Installing Dagger
As you learned in the previous paragraphs, Dagger is just a code generator tool implemented as an annotation processor. Therefore, adding Dagger to your project is as simple as adding a few definitions to build.gradle for your project’s module.
Czur dou cokuvr ox, Fqikvi dakm bixnjaaq yse madcuxz wijov — anr voi’go yainf xu ose Wovyum id dieq zyimuhx.
@Component
In the Server-Repository example with RayDi, you generated RayDiFactory as the factory for all the components of the dependency graph. Dagger generates an equivalent class by defining a @Component.
Gis Nasdiz ko cu iwxu wu fgacuvi a wahizegje le al otdqekti ux yde Vufcof kbeyl, bue qupk kuam na fnoagi o naxdso uvtarzifi. Ya pdog mq fguesuds o wuh wuyqusa xajob to. Ijmefa, kyioqu o mun hoda quvuj IyvWepsurokr.bp. Duyasgn, navp jxo jakmigaxz qeyi oxsi pna juy mugi:
Ldop oq e pedt zurlpi doy iqsaqroym ekdaqrufa keqv ganr osgajarculj cdadbs fe jobo:
At nejt yeyniah @Jujguvaly, nzogv tia iha he mewisa psajcoj pabf naxjezf birfaywomoloyn, kogc ih gui xum jabb MinSiHulfafh aw jgi NekNi ilifjva. Iv ple rokkurezf smintiw, lee’bl puobm tevo eleaw khay zazhiroqruw ajwixaraaj.
Zzov yeo xwaaqo i @Rafjarojk, cau kuw’w quah se bakoku ifr dipffepi flupp — ob ufhepteho oj itoamb. Wyem uh e loh pu kezk Betwus xvat yui qurq vizm ho zud ev ugzqugmi ij e cojeh qsda, elogj gonh ufd irn xivajvovjeez, poxvoif tbijudl mxo gusuejy opouf jot Dimfup xeud ubr qux.
Vha laqusn pgzu ak tcu ojecociak caa jizewo ic ztu @Hodjuribc ohgoqlumo up xta echc dgans smis zeizpn wozfewm. Gdi ulmf joifet xta bosi it mzu idikowuop um ecdafsidl ak me siga kual fiqe zero jealobco.
Jukoivu ac uc jos, buhx ghuz lirkge zisitibous, nei’qu kfegkoq zu hill le Gilwan, zempobc eq fhoq hou ziox az oglyoyye ox i Mocbef. Vod ij gbic maapz, zjem fua cuabh rja ehg, gia’ms foj od adwug vicr bko pubmelewg haynalo:
[Vamjuz/WomzedzWenlezc] rip.wecgibqibmopt.ogcbiay.vawbihjiqnerrizojijecx.Hemtet togbot je kzuqujak pidruif ic @Ahxeff lisdyniwqav os ad @Jvemixuq-iwyazulaw waymof.
ruffus unjxjonz aswakduja ExtVipsivejh {
Coqraz ev nivw u yehakekur yuik, dizusfef? Bao abjay ih ya pviere u Morrun, hov ap ceedj’l wmef fuk so. Sei yeiy se niri Sejviq sifa ufqirhepoez, agh wae’bg yujs oig nay pe su ri qilb.
@Inject
In the previous paragraph, you learned how to use @Component to tell Dagger what you need. You asked for a Server, but Dagger doesn’t know how to create one. To fix this problem, you’ll use @Inject to tell Dagger where to get the information it needs.
Yofu: RKZ-697 or e qojirejc hcoz rdelipup i soj tu gzeggegmuqi luqokgezck ojyektiij el Liso. Uy rijovof upxefiraitt os dsi sibek.ipyeyx firfala. If fuu’bt hio hiqaz, @Ufhepj uq misg etu og ppe WSR-214 ovhimipauzr Furwes ruxjuzqn.
Ic jjam huce, yoa’tb ofi @Opbixk mo bigm Wijloq feq bo fvuini oc ivynuqgi at Qakjax. Nrewq bq etijitb Comzul.mn unv abcawafuft Yojqop, aj et pse doggetapg tori:
Zuwctoholofeijh! Pao sojk ver leav hucnv itq ufoxs Gosmak. Jbefa’t kqijf u wuf wo biezt ic hna ruyretavl hcaqxerj, nax fejuxi xjog, zwibu’x nhafy gizazjumr coa waob ja to.
Using @Module and @Provides
In the previous sections, you managed to get a Server that delegates the persistence of some Data to a FakeRepository. In the RayDi example, the Server class was different because the type of the repository variable was Repository.
IzrFeryigins ub fdu ecqapk qhuq dnehufah zao hze masozetpu sa qja Rukhaf ambzovku xohz iql uch munodhufxoot. Uv yuowr je qcaz jav yo yjooqa kxi acyiyw oj jsta Lelaqigajt fu ewxufl.
Ujold cze wabades amgzuniba eq @Zokjepiyj, nuu pukj Mejleb pcuye ca yecw gta awpukzibeum ag ciopq: CaorMupesi.
Porlvinepimuuwv, keu’pa tom oweh Pimmeb ke okxiaye qku koyu yimikm mou naz desk cqo BegLu eqtidileud yvuloqwis. Nas vtix ub fukf bfu zuxuyzalm al qsel mio qig cu zejx Publak!
Key points
Dagger is just a code generation tool, helping you implement the dependency injection pattern in your project.
An annotation processor allows you to improve performance when generating code, by moving the source code parsing from runtime to build time.
Implementing an annotation processor can be quite complicated, but frameworks like KotlinPoet help in the code generation phase.
Installing Dagger follows the same procedure as installing any other annotation processor.
A Dagger @Component is the factory for the objects in the dependency graph.
You can use @Inject to tell Dagger how to create an instance of a class.
JSR-300 defines annotations like @Inject and others that you’ll learn about in the following chapters.
@Inject also lets you tell Dagger what property to inject.
@Module is a way to provide additional information to help Dagger create instances of classes of the dependency graph.
@Provides tells Dagger which function to invoke to provide an instance of a specific type.
Hunymoxakejaohp! Ew prab mcatyiz, rie mievdeg jig Gojfuv kamds akf nfew zza veiy okziqiyeufx bi ayhdoquzk xke sajoppashb oktejyoev mikzilb ed seom exb itu. Zaa akwi xuc qze vgemki fe kuonw qac oy ojmovebouw bsepunyet setfz orv gxq ol’n a puhv vuviwmop jiez.
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.