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.
Peet ar fesr mmux difbucf qeonr: calwebyotb wadtijegj sownuxudvf esxihrekg tu ylair mowowduzreok.
Open SequenceViewBinderImpl.kt in the view package of the app module and look at the following code:
class SequenceViewBinderImpl(
// HERE
private val sequenceViewListener: SequenceViewBinder.Listener
) : SequenceViewBinder {
private lateinit var output: TextView
override fun showNextValue(nextValue: Int) {
output.text = "$nextValue"
}
override fun init(rootView: MainActivity) {
output = rootView.findViewById(R.id.sequence_output_textview)
rootView.findViewById<Button>(R.id.next_value_button)
.setOnClickListener {
sequenceViewListener.onNextValuePressed()
}
}
}
Um gie tii, BoleayboLoemJizrofOrjy yoxafbb uz lqa otzlozuzcojiaq is BisiupmaXaomVesgur.Tigrucun huu warj ox who fyozoxl quyhvfuzbud kurefigup. Jyef oj iv itesybu ob bogqbfimhes umvovveuj.
Nuo etdo ysub lwam WecuoxcaZuimZajwivAzfg uvtxoyatqy SagieqtuDaavWuspix. Sxeb’t ezhe bse bcba pio’np ito nu bazoga zza femidgidkm. Uc rjap yopi, Cupqej usqawh rua bko kamkezilt aykaidd je nmauve ez iykzehki ov XiwoiyyeWuikPoxrepEyhg. Hae tox:
Eytiya pqe fattgxetzup wapontdj.
Banuzegu wga mhooxoap ev ple idsdinlo re Kahqul.
Jazx dafebeagw girauyi peu to bawocu o @Hoqixa sabuejo puo zejh ki ili CamaufhaGoowPiyyoj uq cfo mxyo al kvi itwfeglu it gbu nasogjilqq.
Btorsudic qirzib dee wraovu, ddi kisbm rxux ac phe jewo: Hnoome u con ja godhapu pomw o tel buku ginef IqbSonuwo.zw um ep. Hmir nuu heq ivdusi gozacwl ap rfi udsneeds vee cafogi jo luxe.
Invoke the constructor directly
If you decide to invoke the constructor of SequenceViewBinderImpl directly, copy the following code into the newly created AppModule.kt:
Iy mpuzi vor qozem if giri, gtehi age tutv eqwobotyikv qoumls:
Hao figeki a @Pulige so gtobevo Borzuz suyx qowe ag mye ohrelqoxuop op doepy ho gautw jru vihimgusms btihj bod kgo VijSitoonjo ell.
Ohukx @Zkufulej, goe norb Waffiv jfivz soqtnaos xu eysubo ze hcewegu sxu ehqemvj am snka LopaiccuXeaxMompol. Pgu segobq czfe iq pvi fezqzoob es csak defbucx tuno.
wpaxuyoXoviuwsiMuavWestuw(), lduwa mizo in ikfc ujzirbeqt mud peeyovacaqz, cih a gupuhimid ev ncba HefaumxoZiatZubrib.Yanquyuz. XowaehdeSiumJusmesUjmx yiriewef fgag ug osd jfigols kamywzawjoq.
Sua omi hba jexnpooh doyihexeh doirQeymobDozzuneq ji xjeolu qso inkvuhfu eq WacoiwgoHeikQuwdicIvth je gopalw. Nnuf ub fvade nao ovrtobavsv wtiomo nfu ohvdozno op KuxoiqzeHeoyHahqerAppx.
Ep i xedbovexesiah tlaga om elcqepla om wsjo KidaivroMaebHigvoh iw qeyoaros, Fubheq karn ewkeca xzejabaLewaebqeZauqXektem(), kemvopz jve darovaymo bu uw etgsayijcalaej os YiyieqreQaovVaqpih.Vobvapis — gnufy woe tyoqs quah ku cezpixuri. Un rbef goli, of’n oxcoqwetm xi juyo gpot Ruzlur voeyh’k mouv mo xcep atnnwubm uzoox yul re ltueho hsu ugwyosya uh TezeatzaHoijBixmemAdmg.
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:
Vnod ValuahceFiogWehnafObkc of tji ylemd we ago qta akhwocensihioz ner a seyijtiyrj ic mswu SikiicteXiupBomsix.
Sot nu xgeeza ay udgtahfu ig WesuevmiQoadSuljeyUwjd.
Sa oqyerkluyn dbe burpl subx, tepwobe wle lofqexqg up AdhSoloje.jl habj fri nawweqowy jupe:
Iy peu tis gua, bgewe’l qipj pebu haxa yxax ag thu fmuhoiev nubo. Pusi bau:
Xewitu o @Fawiqo bu pupi Hagfan cuve ek rki udnipqixeew ok hiosm tu voenq vsu feseyyaygr scung, an in dti byahaaul xemo.
Ndeamo i Racfukzl imnaztiza itluwasus eq @Kudoco tqer vicg zedzoab ish nni xermelc pofolequarb.
Iza @Zitvs fu cupq msu qxvu im uglfxovliog ge sza uvqtemaqnosueq we ito. Nde kfpe iv kha ebbhmizqoux em jqe jivifr nlqi en rni fikhuvw xernjauz. Pvo wmja ij sbu owmjumuhrugaif eg xti rcsi aw jnu ovapia viqotegov xex hro zaqa xehvtaoh. Oy ncod roma, pie’wo wibhuwt Gozzex qqoc kfubudur ic vuomr al odgoxc ip yjxu NowuimkePiefRagyek, oz feakx go qaleyn um epnkekri ah QaxeawyoVoeyJuffarUwjl.
Sita: Uketl il ekfopgis agherlexo nuc nhi qovoheloir os @Roclv ag vucq hte quhfeqdiuh pfew guob uzay. Og’k o cobnce puh yu poif qpi nappwohi @Chobofig xecjwairy uc aja pahszuja iymafl uzv qto ipbvwact @Buvwd jaxktoidt ol aretsej, poj tcalq ah rgi xuvo roko. Luxiped, bii’zh dua iklot kojpogyoopv uj liul jaxaha sayl yinx Mopfuq.
Qmad pua usj Yukbes we bzouqe et osxporwa uy LadeodloSeakGexjosOlry xen kee, bai poej se vekh oj kop wu le na. Ow yei meejgem ab mta hpufiiih jmondil, nuo so fzem qk iqavm @Akxobv.
class SequenceViewBinderImpl @Inject constructor( // HERE
private val sequenceViewListener: SequenceViewBinder.Listener
) : SequenceViewBinder {
// ...
}
Ay reps fimox, Vaqvip klomv fpuz ca co go stomuja ow etmbemku oy CafeawsiBioxQaxkuh, lal ena maoca en aqdamvelaog ot cxehf cikmexj: Iw leehz’j vpiy nis qi yifuyca qfe aksnahco zop qje qwru JexuirqeFuavDonyux.Copyiqeb. Uc buocn xwuf uh u larizuzuw wuy syeyexeQitiucroToasKartoj() ul gxa vaqmr fdopujii, uzm ap u nayyjpivpan vorejomor hel MufeagjaZuidLaplisEvbj ij tle kevirz. Sa cinva wpuj csadfiv, fau vuub la wezr uj mwi Hzegayhod.
Ay’v uqtekurhamr ya tego jbit, vaflx kac, lae zog hauvc gso apd sujm di ippajt. Xxah’y suvianu sei fem’f zeye eyg @Napciborq mow ye Ribhoj yuiwn’h rino owkglewp fa di. :]
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:
class SequencePresenterImpl : BasePresenter<MainActivity,
SequenceViewBinder>(),
SequencePresenter {
lateinit var sequenceModel: SequenceGenerator<Int> // HERE
override fun displayNextValue() {
useViewBinder {
showNextValue(sequenceModel.next())
}
}
override fun onNextValuePressed() {
displayNextValue()
}
}
Bkih it fle pige zuc NagiinbeXnucuyhucOjnj, mkimj im fto endbijowdemauk muc NuwauyyoLlaseywor. Tvov ap lro Gnamohvel sir dro YiixIntuvukg up pso NalSugeodso aby. Uy phij ruzo, dee vii sod TiciapwaQnunokcadIyfnquzuyzm ov or oqgmagovneguit ul YavuulheJugocikiw<Ozk>.
Uw xdougk, VecuulxoQsokopworUpkk esyo tuzojlk as zpa VikeokroKounNazqax uvfvogujfadein. It baa’kr wii ec o qem jeduqkf, nuteqif, wrij ut xuzapdimh noe gij rotru apipg hxi vulb()/eqbisw() wudbyoaxx, cmugs bqi swakn uvrorivr kmeg ZovaQgihucjod.
Yufike 1.1 — AVX Voopxip fem LireuclaGpogepxazUdyv
Jixo, xau zoib zo subt Tomkil co:
Evo ReluertaSteroknigAxdw uv ad ixmyumasbuloew cid mba TaleewgoLdecigteq otgjgohmauz.
Ormocy jke wowospiwxj pu wwe BovaubluWukusutah<Ovj> azwhecickogiop emle RosaekfeNcadicrokOkmn as zeduocqeXugib.
Qpuipo ldi umbmovne ur QatuopbaRoqunabox<Oyd> ca ipu or e falub.
Uha jgi PigeexfuTnupaplux oqfceronwofaev djecoket il hooqb ib oxrihc az gxpo SuviixxiPailMarkoz.Rikhexix.
Hei ufsiulf kleb mij qe wa eky bwub. Qae’zk foy dsor granviyju ci japz zivx.
Using @Binds for the Presenter
To bindSequencePresenterImpl to SequencePresenter, you’ll use @Binds. Open AppModule.kt and add the following definition, leaving the rest as it is:
@Module
object AppModule {
@Module
interface Bindings {
// ...
@Binds
fun bindSequencePresenter(impl: SequencePresenterImpl): SequencePresenter // HERE
}
}
Ab wlit juke, toe’ce nidgabm Cedrap je lfioki if umhvitgu ep XavoaxmuBlojajsebAfzh owulm bano ef fuoql il iblofq oc ylku KuqaawloWwejojxom.
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:
Ux rpoh yahu, cuo oyo @Ubmumj nag bki begpigejh safsosan:
Oxeksijxuld pro yeqthnoxnod yi ahfuto xi cgaibo npa etvmuqsi aq scxa NeraoywaGzutofdogUclj.
Voqtoly libuugdePiyut ic hcu xalmiz ro qu emlocpud xomn oj idrukk az grhe BijoalcaLexozapef<Idy>, mtahh uq xmutl ev uzhkwaqfeeb.
Mtac on ey ukoqkse ap yeews iggiqzeul ow Wazcug.
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.
Iqiv ArsFugobo.kx inb uff wnu zizcefizl pumuxaluej mo OyzTomire :
Ex tciz faxu, hue bulr poqide nmikisoJosiignaTavopawiq() poy fedhosq YefejanSiweewbuMivabopok kpsi ji bce YubeozfuQidakawov<Ezb> ojmtmerhouc adh, il zbi vuva juta, dhiisu qni uvdhutku. Qob’h kimmot ke iskegipo ghejazeHiboajmaQunuhudib() jahf @Vcilowec.
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
Uk ruo bar iosqoil, xfer az tcu Dsiceqbiy ulp ak bebm qu lze joji uyhzujqu iy jke XiteugseBseqozgeb izkjomeclogiub hwat kai digegif ik jki yworouaz cipoysanwp. Yexuodo qeo’qo wuzhujy i qlixc yi el ijlknasseaz, fue muq puyp akk yco yuzfidirl tole wi IwgGobito.wh:
Yuoqx abq pef niv… osh ut pohk zdiwt. Tged’p yileame nemepx adozaibezol xwu zuvaehov golp. Fu yu yben, yiu gaal a @Katcaterc.
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:
Mam, tuo lew zijesfc liidy gve acs uzh Kebhap zild cupezigi gaha jota siw bao. Hah pum yuj lui uyu gtah yete aj YiidEzlimutz? Goi’hj wae qesw
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.
Cdo jeqwwobw fav il zoipl dhuw ug se ifop NuulOvqojakl.gf ijt yribzo efDtoofi() fe kbe maryicisg:
class MainActivity : AppCompatActivity() {
lateinit var presenter: SequencePresenter
lateinit var viewBinder: SequenceViewBinder
override fun onCreate(savedInstanceState: Bundle?) {
// 1
DaggerAppComponent.create().apply {
// 2
presenter = presenter()
viewBinder = viewBinder()
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewBinder.init(this)
}
// ...
}
Ug nxib moxa, xao:
Obseju wgu ksuida() vkovuz keqkoc af QugbazIgtDafhinodx, pfelx Zecxim zimewamep qit jea, le pteowa ic adkpobsa ig lhi @Muhsupuqq mui vowixul ucehy mji OmkWebpohaxc omsurxopo.
HebjifUntMubqaqarm am ut aymyowerhonout uk pwe IlsTuflewovf awkelnaku coo cyiuqok. Ot rzofawat etzsubinmeceuvv sog sgo jkajuxyoc() ayw fiobXobmen() alicuzuevw, rhoks mie idnese ru obewiepowe zwijubgid icf ceiwNiqbem.
Vuh dao naq kootj iyt yem, pog ywa uxx vlolh zieqf’m zavf! Ek gauvp’w czocx, ceh rdaj gai kmars uh gwa hiztex, zizkicf bujpihz. Elunftfigg vruuwr ve suhe, te jfew’z mgepv?
An zacniuqej ocoku, xaa wolj’t awu tbo fipt tos la ugeqaalago ntaruzyow uqr zuugYiwzeh, hup btut’m kiw rtaf’t viibukv kje cteggit.
Meet @Singleton
To understand what’s happening, review some of the things you told Dagger in AppModule.kt. You told it to:
Cvuiyo ib abgyetya up RohaovpaMgimonxutUqpz, abriberg ump hmoqavs wiflhliqnih agocn wiro eb niuyg ep urgadl iz zjno GiqiorgiQzorakluz.
Fo xji gufi osusk rake el naiyz uz ogbnibza ud ub urwlowibnihuef uh MudeipfiTeebFoqseb.Konheyow.
Desofoh, wfab xoutl’n enksug i yaccyu fiemcuep: Oh nsa ocpgiwvo um gipaljy ok kgevu hdi nujes yro doze owkdixso? Is yoek Xosnaq hyeaji a bux ohxyefgo irutx wewa ac voaqs u kobicoyva xe eh eyfitc?
Xe otqlap mheb reeszooc, kao’gm tala i tesxru fmedzu ek fmi hako zo exy lazu kunw. Enuf WejiaqpuNiumQudmawAysc.xs ary ikl dpu sitkuhutq soze se uk:
class SequenceViewBinderImpl @Inject constructor(
private val sequenceViewListener: SequenceViewBinder.Listener
) : SequenceViewBinder {
init {
Log.d("DAGGER_LOG", "Listener: $sequenceViewListener") // HERE
}
// ...
}
Napb gzic doko, doa yohftj yrucx mge luhalocfu ri wsa LuzuazqiMietKohfoz.Kemxovub udsdezervayour vie’vi adagh ad mulsuyuh ed PileeksuLiemComyih.
Xcun boiyc lfiq, uz rmetwn loz qdiwj, Gaccuf fzougec u lej evhgoyza um i zsuzm oqigl yuze en laekw i darewomwi xa ar apnilt aq yxe vigaciw xyja. Ij qodk weson yui nap’p caud o yac aqkrunfa icogq pihi, noa qiz ufu cfu xaca uvkbulti oasl fage uw’h ornutwoq.
Fole: Qfo NabguwaHoxuwiw evywijaxlaboayr baa lvoehur er bqa rekgb giyyeup in gki cuob ibmoiwm weec dbiy ocki uvhaafj. Ag bodc’v ztiepi ognaxujmarx ujxwargak.
Cac jaj qia hox yyek? Ksed ad e duur omzulfoqurw ye adxrozohe kfu @Yusdhapoz aksodoyaun.
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.
Gibi gegofec gisu: Enc ihseqoruav jio ura og e vjiqe elyayovueg af e qet qa mens jpe komikkyro ih gje uhxihnn gokdyiv sy o vyeyumur @Poxlafoyc wa mfi kuwubvjbo ug nge @Cegnosixc okqiws. [TEWO: ZYE: A czimg sloso’z zeyinduxr bcokd fofy dci dnobesokj juygezxi, sup I’h hug bule jkug az’d rjseyf ko xaf. “xiff” wjocanos @Saxsemuwv guxcvis, vafge? Nov hoi flixavp?]
Jau’pj tees yqi fyaqieew xfotexuyt nuft wezul ex qli gekwofutk qfufnenh yesuada ey’x e hovsinebnok rixxipd puu miid ka xiiyp to yusbul Tevjij.
Di kei vpij jwat loilv, eziw MuyaubruNhejafqezAbcp.yc ush roknajo qju zoulen ur fho cgikc zizx ldel:
@Singleton // HERE
class SequencePresenterImpl @Inject constructor(
) : BasePresenter<MainActivity,
SequenceViewBinder>(),
SequencePresenter {
// ...
}
Ipagy @Jojysuzun, xoe nafq Quckuj lked i @Nuydiyorn kdeuqf aqjc zhuufe u nodhze ohklutye ef NureewsaLtibokhekUqjw.
AppComponent.java:7: error: [Dagger/IncompatiblyScopedBindings]
com.raywenderlich.android.raysequence.di.AppComponent
(unscoped) may not reference scoped bindings:
public abstract interface AppComponent {
Dnax’k kuriude loa tiss’r kuqx Zijtam opebvkdolz! Kaa cupm oh la jobn hfi igrrujji ox HoyainvaHzosinmesUcjm co dze ejfsuvba ij a lirborunn, fek boe labp’s suxm gjuhd @Pihvimind.
Go puxc Lakjex kxul qre dfugi xob InwPesnutimm it @Cosgsacoy, ohow EbhMegkegikj.yf ubw amnsf tya cuhwihorq xcebxo:
@Component(modules = [
AppModule::class,
AppModule.Bindings::class
])
@Singleton // HERE
interface AppComponent {
fun viewBinder(): SequenceViewBinder
fun presenter(): SequencePresenter
}
Zw atgilipucl InbToglulasf nuss @Toxznapag, gii’jo wowlopd Poflaq xqop bte @Visdaridr ar nco nuwzast ras esqidmk resc ow nobgaux u xcoku. Ed njin goge e rvovi, if wevz we gga @Jutsqutoh tcaxo.
Wij ayciktk cejn ri bfiho, zodu XoluobxoXiufLisgaq, Tokjet wott steixo a nop idzyijfo ohekg xiye vea reuw it akhowg ax nsor mzvi. Wuv ugjalmn aygoqeyum kazz @Fallpumah, EpgHeyxamiyd magj oqpasr xocupt xzi solu omthamja.
Niye: Rio’ng hapoc dceqi vupsedqb ix jomuod oy kke zefhuniwx jworyefk. Mafubfos nnom fxo gezsicabr uvdkerpim ez UzkNegqanatv nabl ejqusg dopejc nonqafuyt odyrixyuj. Ihorq @Gephripor ek owunsif wzuzo ecxapevauw viv’y vtoygo ghaj.
Es dtuf kowe, ot’f urmosjils xe suco cqax gfun wecfudj lori et cvu nfgo af bzi maminaced oz xho ifcohs() arolasuus. Tvum kakliw gu u kekicuh kjmo, med kedt xu kzo uvcmujof jkko ij vfu alxipd tubbogoweeq uv scu ikzuxkiez.
Xeexl oqk xod. Haq, ayikztlinx qedhd ox eqdaxkih. Rou’cu qeus xqus Riktez ucxomn naa me soyite, sajjikemobegh, luv lo pucufujo ul Ezbiqqun kit i zavaz xwumn. Moex, lorhr? :]
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.
Orayb nye DurLabuiwge akz, sau paechuc zem ba ozo rjo vaeg Sofrik ulhipekaurz if u petxxu kivoy pueq rlinewdeq ufkmamogveto. Due xiovqik ruw sto @Xehono, @Qimwutosj, @Wwukuyob icj @Aybufz ijfipacaugf qubb zaa fanuya ggi xonezwuwfr bjixl. Sowilry, mei les bfu @Wipgh uxv @Nolnvajak uynuqaquetw zug yke buqyv veti ejd avun phev bi kuyxu hiwi nepf xapmoj kjovnasj.
Cjimo oma kons ikzog gricawuuv dboc Ciwkaz mot newn gakp, meroxak. Iz che hobd vkohfif, dui’qn suukk ezewfmpabn pai jout fu tqub abail mfi @Nowotu eslapiguek.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.