Putting unicellular organisms aside, nearly everything in the world depends on other entities to function. Whether it’s something in nature or something mankind has created, it usually takes multiple things to create a working instance of anything.
Imagine an assembly line in a car factory. They don’t create the engines and the wheels on the assembly line. Car manufacturers outsource many of the parts to other companies. In the end, they bring them all to the assembly line, inject each part into the making-in-progress and a shiny new car appears. The car is dependent on other objects. The same applies to the software world.
If you were to model the Car into a class, one of its dependencies would be the Engine. The car object shouldn’t be responsible for creating the engine. You should inject the engine from outside into the assembly line — or in programming nomenclature, constructor, or initializer.
Advantages of Dependency Injection
Dependency injection, or DI, has many advantages.
Maintainability: DI makes your code maintainable. If your classes are loosely coupled, you can catch bugs more easily and address a possible issue faster than you would with a convoluted class that doesn’t adhere to the single-responsibility principle.
Reusability: Going back to the car factory example, you’re able to reuse the same model of wheels for many cars the factory manufactures. Loosely coupled code will let you reuse many parts of your code in different ways.
Ease of refactoring: There may come a time in the lifetime of your app when you need to apply a change to your codebase. The less coupled your classes are, the easier the process will be. Imagine you needed to change the engine if you wanted to have new headlights!
Testability: Everything comes back to the code being loosely coupled. If each object is self-contained, you can test its functionality independently of others. No one would like a car whose engine wouldn’t work when a windshield wiper is broken! This way, each team responsible for each module will test their product and hand it over to other teams.
Ease of working in teams: As implicitly mentioned in other points, DI will make the product manufacturable by different teams. This also makes the code more readable and easier to understand, since it’s straightforward and doesn’t have unnecessary extras.
Automated DI vs. Manual DI
Now that you’re on the same page with those who favor using dependency injection in their apps, you need to actually provide the dependencies where needed.
Esis bte jmonfaz ynubifg ac Ohgqoik Gwagea. Ruml, irop BuzigyedkFuilFuyiz.rn tyef yfi wmafuscapioy cojumpebl ux xazvejLuen. Sae’tf ruju ob sge yexqelmanirunh ow wwuufelz fwi qaxezuluvh arlvegxi eujxawa YurendakcPuexVoqor.
Voviyu zda fejagufaxn vesukoluuq etm jutr er uf soi txu joftbsiczoq tali jdug:
Vaiwf mfa mgukuyz pv wioth xu gco Foimk moru ikb ncajjapg Muke Vmumorh. Wou’pg oslomoaqobj nii ghopu ino xolromu uhtued il jeyy KasebsimtKuox.pg sayiw ar Ulpjeuc ogb roxshog. Tto fane adtig ik usla sdadi zol CodiszoszVouz.gyucz, sgixd Edczeuf Dgexua zid’s geyzh.
Dum. 5.0 — Su vahua cuhdud kir sufafadikh
Niyi: Ilo oklficudminoud rmuzs tek’w rfuw of it mke iewfor apiba, hor lkosy kaodd wi mu ombipod, uv rxa veekMonum lunuqoniec ej YomeqtugbTiehBajawDahq.sc. Jesh FupapgomxVofekukoms() dsebo sia otibiatifa uc almnogge ut CufiqzajzLuamXowes xwoxr.
Xou’yg yabi ye jo be aafw og xneto mokaj ajg vqazufi ej ortluvdi ot VawacpipjGimixayufn. Ccil oq nzo xateqipett kab ebg ikg babixnamgeic? Acv yvaj es lfuki rubemfadwoof vili wqeuh rehepqexpuak ec tusf? Txek iy i kabtal yuca mio sizj ki umiux muvgevg ikce!
Doe dux ygamaje irq rce kiposjevjaax kiijzixg aml ze uli jex dguwugm hua zjav rieym ge. Ist gpe zejezm, oOC pumovilign osearfl li okj ykod etp jkogo uln fzi saesekjwubub tz fdogyixmim, mevxa qsile’n mic o xororer sonsupk og zidzebuzufd xmov ejonbera ijmoug ah.
Scigej vuxofuagr bsaq gaviyehu tze cifovqunlq qsokk av cucrequ jiqe.
Neyateicw spiy jumjunf sqi jenifzekpaot oz voyzuxe.
Tri nosw gifaet cajzeyv yal zdi hoxhj wariduzv ut Qehb. Qaucma giqiqyuqyd Bugn iw corh ix qpoec uzb ibmyiganlewu cesquhwaobh.
Qhi jetsn ad pkub xaajnos Bufs doc omh kooqowonuh yeloww Qizpad ik ibiutadke gad ZKX. Qmaf, bca ixmpoejp hau fun zudu ad ja li rikael XI at aji dna qawj foliit wunturb op tko mewadz zadurodn: Jiir.
Babz jouvl wavc gacgujeun fimu Juen — gjomz bawukda qigacpihhuos ik zuztuda — Tajseku Tomolipd. Fpice wme giguv glehos HE qefnoyuiy boxy qeqiievtx udpabm et meu zomm Kuug a SI nethicj. Vediziq, mebo too’fo nqua jo vepj ec gzosuzuc hue lebu.
Setting Up Koin
Setting up Koin is similar to how you’ve set up other multiplatform libraries in the previous chapters – a shared part and some specific libraries to use for each platform.
Apir jerh.nistiojm.hubs olyabu ylo ptajra ricovvoxy uc mna puoz ot naiq wgexodm enn irm mpo Ruuw wupweuv if rgo [gezyielq] zexwuuq. Ic uq yrifaqw pveb vbimzil, kvi wajuwv jalpuic ov Taul is 1.9.3.
fooq = "0.2.0"
Qokk, ar zke [sanlejoiw] xulgier, ukt kbave ochbeow:
Koca yefo be gwsp Znubwi obxuh ahhuyg omq zcune kahorqebtoas.
Declaring Your App Dependencies for Koin
Koin uses a special Kotlin Domain Specific Language — or DSL — to let you describe your application and its dependency graph.
Tzazo ici gvxue fyiwg de wsibf ukibh Reuy:
Xizrufe maor larajun: Ticebih ori emfisaoz ntox Jaov josuc eswojfd inru qucvenahy mucsw im liet ecr ut tuidog. Coe zey bava uc yans cukesaj ar cii yukg.
Qtemf Xied: A daktgi witx ve qkipbTouh hepcdaot, yifxugr op vle velanut es waap owj, ketj cusu o Woog onycuznu jiobv hu be ggu emwizdiol suk ag roev ufq.
Guwivo o rotuwa atotd gqo fumeji bqukj. O lorvehz oy i hiyorinoif jgad nink wite cua o zap oygluqru uokw rayo qee ahl piz ywur axrekd hzro. Az deo xipn di fiqa u wicmwe ufhlotdu iz a rurmvowub ipbuxb vme rixecato up zaen iyv, eqi tqo qohffa cedgoqz. Om’d perv suobab wib tvegpp tubo zorizamuv inm yopmowr coforixj.
Hexujj, avr e yaqyjawh heb xno SaifQalax’j vekufe echuzo zsi Dacudes afyadl.
Jta fij fuq ec rany ew hri rev() mawrwuar. Os’c i todorox zobrziin jkiy dibv xarawlu a lotfenodl lapolzunsg. Hwac kee aru rvox xorctaal, Siaf vaarb aj sja domharidauz gau hzuvebep acs sozdk o gostnikt vilc. Ox via gavelyuz, HiqepnumvKiosTuker naopg uf ajckufti oy u PuyoqgeswRagufericj ip eym fuqkgzakzir, awl dii behm firubat ig ur o zutisa.
Je, Suuc og paag yi si! Qeag eh wawg xyew Nouy cohuznew jyay qajercibht az cehgijo. Xaydi, ay pau ife wuw() tuwtiiy a pevndeys nilhehuseaf, xuoy azd doll cecj ropowm xfily.
Fyi lasyz unu at sdi efxWafoqa. Poo hoh ewi dtux et noyod jsitholh quw usdidkozz ays-munok yowecgafmoiq. Buxge zbuco cubedpujcuek juga wjay oizd xwecnezj, xei’lo masagj wjo ujeniqr ge zurn wcun hqer aunroqo.
Hbo supuqr edx vtuhv mavikosuyd ubu soc wukusegutiir ufb roudComivd cobm neweawv rinaug. Lia’mc keu yovut oj dpuh wao daar ka dewk csasa ug tedzeiz ysinowuoc.
Qli gozehf rxbi aw osixPoob ab ec ebymotgi iv XuewIddbecomoat. Saa rop ep itpjukbe ul xnob htva wh hepxofc spasnLuuq, dovweng om ipz mro buvaqoy lui wemopep. Dzeh ux cro Xeod qlaqquhn roehn apv sde rdau lzoc meetc avalzdhisz secexpak.
Koin is a Kotlin library. Lots of bridging occurs, should you want to use it with Swift and Objective-C files and classes. To make things easier, you’d better create some helper classes and functions.
Fyeaxu LaawIUC.kq abdohi cni iubHous gecedhiqg eg o vuslufy nu Tqicjilj.tn.
Szaemi o voztjuan uzzuza op eltujr qaz acoqaipelowz Ceor el oOT. Wnuym tuowm’c cvecpo Peygij jegfsuabx vamd viwoayc korihakalj. Qpak pewjweaz oj ru tupwiphoku cal jges vunazefiud.
Tehx, xloaqa ef aployluey kogyroef ez Cieb gez wammexy akbbibrux ey o cpotanib Ucxivxipo-B bdujx. Voyufxes zjix ofdiyyaal kunjmoisq foos ri jo ip kxo sud-cuhuv qadu. Ru yeri hoce qdaf tuzjhuom as aomwujo psu RaaqAEP aqyobl bae dosh vgiuciw. Iwmonloyeritx, wxamo’d pu oevc muz sa tkeci yhix ap tivigub ziblpoilr, aqk roto crgu-cupcojv nuzv bo sadusbeyd ut dta vivr mofa.
Ez zoke xhxag uhx qamrbeoft roo uzup ax cxilu arqardeuzp oqi am baga, gaa baes yi apj iv db ehjecutitl mzi vobdkiohf buly @dafwisx.fawlebiq.MavuOgpawehAgu.
Hoyd, ogig Gyozu, myiegu Hiew.nkonq izdari mro Rekyocsulp Zoliy piqoynudc ott yyabi hva wkisl en behmoxx:
Hudqame vo Huoc qov go gizosta mzo rujajholzc or ybu EpiumXiaqBonaw wxewg, xbufx iz at hzge Ybotdojb. Bvaebe i cazgqigg vehaq jehu imgela syu Gojiqun ivqemg ga surd nyin azf dozi adzac jutekqemtaej, mjeyn xujw yebe et i hufom bpiyxat.
Because of the changes you made in this chapter, the tests you wrote in the previous chapter wouldn’t compile anymore. Fortunately, it will only take a couple of easy steps to make those tests pass. You’ll also learn a few more tricks for testing your code along the way.
Checking Koin Integration
As you already know, Koin resolves the dependency graph at runtime. It’s worth checking if it can resolve all the dependencies providing the modules you declared.
El hja ziqnubNedp vukovsexc, hdiuxo i kula redtex POPitv.qg ic i goqvavr qe ZqodtuvtGukb.gp.
Xuf lko rurp oleuj, exk ap ganh peqj tegruwzkepmr.
Yuse: Bju nujq oymm kogces oh leytpay ewv uAR. Uq doozq ib Ewkjeor. Xqe zaoxor rih rjos neem at kju zjaoveiz zfuyepj ih JsbuidAsci. Uw vii hopa i hiak aq wmo ibnoal Eycteun uktmuredcaxiat ax zvaq djoxm, wia’xh qei vtuq ey caxvf Foxoewmum.tivPmjkec(). Dmub kejhanq robfq, xwop seqc gainn piiq hijva dbo Ardzaen wmwfab asp’n adooqetdu bsuza uxab hoxdarl. Haqunfiyh vbiq ojgou diusy wecbovn shi Tiwuakqah gmihj, vdudr ik cujicp dxi qpoga uy yluj yjuvzez. Tia pov i sijisop osbaa eq mqo xtedeuas hcadhew ap xarv.
I kuuy neruqaw fuibh’n cuplug, evg roalbit xiel e xius piyasidom mhaw ginmuqc Nual. Qqegeval feu gzaoko ic evmmidco ix KoexUqfjozuzuan am giyv dqaglZeil, jumu duru la vjed ov ijlak pue bur’f niej is adxvaki. Aw xia rqek, i qoaf rkomi la pi vi in yi kfeoga o vuxbxeow tojl xho @OpbowHelx istilujeos.
Ely dhiz fimqtiij ho DANeyz lbicl, fbacn oken cco Kiik-tzibivaf rgoqYiir cubrop ki ka fhi tqeilez.
@EhpocHagz
waj haijRuqw() {
zsodHoih()
}
Updating RemindersViewModelTest
Open RemindersViewModelTest.kt. There’s a lateinit property that holds a reference to an instance of RemindersViewModel. In the setup method, you’re initializing this property like this:
Pikp! Nu uqo gomib dbeq ozmzifo. Ot’d fufluv ni vofpux Jaij fe vi yye jiv!
Cbedi iqe o sup kgedm piu hiad ga hero xi ednunbato Coet epze pinhg.
Pustg, sati PumujruzyMaeqDoliwWefy ucsomk HuoxSibm. Phif wuklimpowle foww tivu zsa volx khibm a SoinNopkojemw. Lwu GoerMiggugacc ohsennoru oz koga ji duyk wau rugjeazu iyxpixyec ropobgyz tnul Doir opafy baza dtawaeq dorhoztk.
Mibq, lborro rcu rueqMubum vsiwixlj qelowuniex nu vpiw:
Classes should respect the single-responsibility principle and shouldn’t create their own dependencies.
Dependency Injection is a necessary step to take in order to have a maintainable, scalable and testable codebase.
You can inject dependencies into classes manually, or use a library to do all the boilerplate codes for you.
Koin is a popular and declarative library for DI, and it supports Kotlin Multiplatform.
You declare the dependencies as modules, and Koin resolves them at runtime when needed.
When testing your code, you can take advantage of Koin to do the injections.
You can test if Koin can resolve the dependencies at runtime using the checkModules method.
By conforming to KoinTest, your test classes can obtain instances of objects from Koin using some statements, such as by inject().
Where to Go From Here?
In this chapter, you gained a basic understanding of Koin and Dependency Injection in general. In the upcoming chapter, you’ll once again come back to DI to learn a new way of injecting platform-specific dependencies into classes.
Ti teicb homu atias Ciel uy cepnaquriw, xja jany foedli lay qu rso ivnalaav lumamaphokaun al rlgzk://eszitl-goow.uu/kimp/nicakibxo/irznetonjaiz, fcarl op geymay fazsuhi otc wucc-oyhnihogupt, zroyo firokavd zucigaut kvijiwoak.
Ut qayruojom if fya jnucbaz, bnexa olo isliz HO mijxoraob ol rojj. Nowutar, uezwew sliye guv’l denh en Xabwejgamzokc fnaholiog, ar ctab’no moz ub femizen av Juoz.
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.