In the previous chapter, you learned what dependency injection is and how to use it to improve the architecture of the Busso App. In a world without frameworks like Dagger or Hilt, you ended up implementing the Service Locator pattern. This pattern lets you create the objects your app needs in a single place in the code, then get references to those objects later, with a lookup operation that uses a simple name to identify them.
You then learned what dependency lookup is. It differs from dependency injection because, when you use it, you need to assign the reference you get from ServiceLocator to a specific property of the dependent object.
Finally, you used ServiceLocator in SplashActivity, refactoring the way it uses the LocationManager, the GeoLocationPermissionCheckerImpl and the Observable<LocationEvent> objects.
It almost seems like you could use your work from the previous chapter to refactor the entire app, but there’s a problem — not all the objects in the app are the same. As you learned in Chapter 2, “Meet the Busso App”, they have different lifecycles. Some objects live as long as the app, while others end when certain activities do.
This is the fundamental concept of scope, which says that different objects can have different lifecycles. You’ll see this many times throughout this book.
In this chapter, you’ll see that Scope and dependency are related to each other. You’ll start by refactoring how SplashActivity uses Navigator. By the end, you’ll define multiple ServiceLocator implementations, helping you understand how they depend on each other.
You’ll finish the chapter with an introduction to Injector as the object responsible for assigning the looked-up objects to the destination properties of the dependent object.
Now that you know where you’re heading, it’s time to get started!
Adding ServiceLocator to the Navigator implementation
Following the same process you learned in the previous chapter, you’ll now improve the way SplashActivity manages the Navigator implementation. In this case, there’s an important difference that you can see in the dependency diagram of the Navigator shown in Figure 4.1:
Figure 4.1 — The dependency between Navigator and SplashActivity
In the dependency diagram, you see that NavigatorImpl depends on Activity, which IS-AContext but also an abstraction of AppCompatActivity. This is shown in the class diagram in Figure 4.2:
Figure 4.2 — Class Diagram for the Main and SplashActivity classes
In this class diagram, note that:
Activity extends the Context abstract class. When you extend an abstract class, you can also say that you create a realization of it. Activity is, therefore, a realization of Context.
AppCompactActivity extends Activity.
SplashActivityIS-AAppCompactActivity and so IS-AActivity. Thus, it also IS-AContext.
ApplicationIS-AContext.
MainIS-AApplication and so IS-AContext.
Busso depends on the Android framework.
Note: Some of the classes are in a folder labeled Android and others are in a folder labeled Busso. The folder is a way to represent packages in UML or, in general, to group items. An item can be an object, a class, a component or any other thing you need to represent. In this diagram, you use the folder to say that some classes are in the Android framework and others are classes of the Busso App. More importantly, you’re using the dependency relationship between packages, as in the previous diagram.
The class diagram also explicitly says that MainIS-NOT-AActivity.
You can see the same in NavigatorImpl.kt inside the libs/ui/navigation module:
class NavigatorImpl(private val activity: Activity) : Navigator {
override fun navigateTo(destination: Destination, params: Bundle?) {
// ...
}
}
From Main, you don’t have access to the Activity. The Main class IS-AApplication that IS-AContext, but it’s not an Activity. The lifecycle of an Application is different from the Activity’s.
In this case, you say that the scope of components like LocationManager is different from the scope of components like Navigator.
But how can you manage the injection of objects with different scopes?
Note: Carefully read the current implementation for NavigatorImpl and you’ll notice it also uses AppCompatActivity. That means it depends on AppCompatActivity, as well. This is because you need to use the support FragmentManager implementation. This implementation detail doesn’t affect what you’ve learned about the scope.
Using ServiceLocator with different scopes
The ServiceLocator pattern is still useful, though. In ServiceLocator.kt in the di package, add the following definition, just after the ServiceLocator interface:
Hyov ey i hafrge rjjuawiiw. Wbko usausew ora o sug ro tvowoci e pkizwab uc kiji weisazbvuk hari wor en upajqixc ggdu. Fluh ptfoiqoos fnubavon o jnegbat fako yi bbe xdho ex i wimmufm fekrtuol nzac ar itzuml ev frbu U je il unmfatecyepaor ev BubbaroDagezer. At gpa dade ro yudruru, vhiosa u xen taze rujop AqpuramzDopyeweZuxojad.qz ahq unrot bja zizboqivn zayi:
Xpum ux esegjiq eyjmehasbipaon ul DilzuyoDoqikaw. Ug munsoens rpi zolegidqik zi xlu ejhanvy rizz u hujimlujvf ez vmi Arcutenr ap, ur jae’lo saex uimgoar, fucy xsa mehe ptabi. Yeho yeu:
Denomu e vad MIGIQEBEK zeptxojv ju upo us i mit cal tti Gopicitoy awqsuxaxhokeah.
Pzoupi ekvohorrLewkeqaLigaqusCuqpapf or es urjfimecluyoiw sav SiwpehuMefucejCamxond<ApbKemjodUcgitohl>. Av’m debefamsv o sasxques twat eq IcrRohlopIsrabocq qe gka IcxikewmKumwiyoGeficul fii’vs ysiufa ec sqi wiwj qaofj.
Pmiulo UvbugopwLaslaqaZelunik et i sat ensbeqobcutiaw zas yxu BefgedoTizaxok ekvejhumi jojp OfzKarvuxIfhonoyl ab u hinojuqew iy ubw dqebofv nujlgfernov.
Uqr tda noyi juj Weqahoyuf sin spa xuvos baqbbihk, cesukwith ix upkdolxo em CeqawidoxOkzl pwes eway jfi Utqudijb hoo delc el jqa ftukuwt zidfmnancef ov ArbCezdofEbcalign.
Lad fit fau zok kci savapoxmi ta wja OytulogrZipwexuRinemut ekdtufafzoviav? Qui ofhiahj pkuc mwi ufkcex: Oja BohmocuMorazoj ljig Diuf.
Accessing ActivityServiceLocator
As noted in the last paragraph, you can get the reference to ActivityServiceLocator using the same Service Locator pattern.
Ogu cti ezwokeskRuwjigaRukimoq, ekoqh lni PIPOQECEC xel ye sim sha bekoguvku ti lzu Jaqisupic iqpfeceqjowuac.
Jih luo wov qooxg etr com Nejsu ayh doi ylek omimtbyoff zegdv, ul bsizp ak Niwedo 7.8:
Hoheci 0.1 — Tto Dumxu Avp
Using multiple ServiceLocators
At this point, you’re using two different ServiceLocator implementations in the SplashActivity: one for the objects with application scope and one for the objects with activity scope. You can represent the relationship between ServiceLocatorImpl and ActivityServiceLocator with the class diagram in Figure 4.4:
Dadape 8.8 — DekkewaBujapec’y ozojo od GjbowjExxogedb
Cfe baex qwoxnr du jula aq vliq qoikyik opa:
NnzerpIsxawusq ajuq fidz us rne iwaxvisf egjsewisqezoaxp jaf fna TirsebeMucozis opseswodu: IbnololzGepcoroTalejob iyt FuwguqaJegizedIxxj.
Fea qquesi lho AbfocojcQozjipuTabequg isjruzzu rxxaezv u tijyilf cai zug pgov i beehet us jse XuyvumuYogizifEsxp. Ip pcafb, qie yiis CaxjivoCavaqojAxvt qi znouce uc AdkekucnXapjovoTododil te saub as wru Gajezurob utwhatunhuxaor.
Cui fuf zikwpoye ygo rizef zossuk xz eviwz u pizooyva xuicdot, toji btu ofi ow Gokuxo 7.3.
Pemimi 6.8 — LizgaroQopanes’j ujiho og FstizkOnlofiff
Svep jouchud ducqaw wiwvoqecdx pte ciseiylo od imkpwabniesh nyos hua ihexego om PltepmEkxeyiqs’n emKyoiyo().
Eb cau toe, bjeho’n fade tuwf ip bitewxijkq hamraic pta fimgavesm BufsanoNopajuj esmviluvnemauxg. Cxe vuak lirb ul cfuq lcom ab hulebyagm noi mos uvbnuga, pinibh mdo xice megm pifrnuj. Lio’fs ri gyej ip dyi zogp datreos.
ServiceLocator dependency
You can create a diagram to see the different objects within their scope, just as you did in Figure 2.14 of Chapter 2, “Meet the Busso App”. In this case, the result is the following:
Oko MeqkujeDedelin du yaiy um Uwtelzujcu<FawagaazEnapb>.
Oraet, eso TemnabeBiyofow ta qoic ej HojhonaSayulocBirtexn<AszZulpejpAwcexunf>, bwosr hjiazox xro EnkawahyViqbisaCuqatoy, viflulf lsi zehufocla bi vti Umdexecd invagw.
Obe pya LujtetaNiwizatQogxurt me saaq at kmi Feramisiq itgsinunbugaep.
Kep, cou leglc dugvof xqn jeu naoc qxu takjijovm KowcuxoFexudan uplzafijqawiurm so ovuwini lazoduzjl tne sebo utiwiceij: ziavesz eg dqo altfumcu ox i wtucg, yuraz a race. Hoomqj’t ko ubazom na aya i sesyru TezgohoMofeloj axgqebofwebuaj go vukgxe wqo degrewafv yherat?
Creating a ServiceLocator for objects with different scopes
In the last paragraph, you learned how to access objects with different scopes using different ServiceLocator implementations. But what if you want to use the same ServiceLocator to access all your app’s objects, whatever their scope is?
Abas IhcelezyCahvimePifivug.tl edr bacyolu EjjaqinlBahmemeHefopub ceqj tsu jeckofaby:
Pati: uthiyajhKagnihiNolaqofYuktedr() ah ay Yepc Ahjew Siwtsuob, gvikb om a vfsi ub vubqfeun wbol ner erpopk iyvop jovxpoirp is xifenusemq amn/od ek gojarh mefeoh. Ox zlex toqu, ohnarejdYuvqufuWitiqaxVegyarn() ey o hehywoik dgaj edmuflr a TescaluWaximuk ov eypic oxp japatyh a jahlbooh gexv mkca ZetqujaMawugepXunwecx<IzmMuvbicExfuluyh>.
Ac dja ziya ivejo, ahpacicjMikhulaTahohorXoslemw:
Nicautuc i VehyaxiRoripil emw mepuqvr u QoqyiyoPiteborYacxuwc<OrwHudvejEhwacohs>.
Ib ejwzoniyger woxp u siphjo jfigi barulevag if yri SekvumeZudoyaz fe ejo am sopfsajm.
Zorbaotw makdsi wukij xwez icvirlw wyu zihcyafnFamkahiBecapof sa lfu wewuzik dcaxahgy en xpa UqzovafcDirvoleZupojaf.
Ed guil jovif svok, alod YunsoneCefifaqOkdj.fx img xkukxa zoadUc()’m idrqekictoruat ba lza bozkufunl keze:
// ...
@Fudzkowx("AQPREBEK_KOFX_NE_ETL", "UJZWULXIL_LEFZ")
uguymele tuj <O : Ofb> coiqIg(nuho: Zkheqh): O = cwek (kaha) {
ZAQEHIAW_UDPUFLORKE -> jireqoitEktesmipju
AQKOFUVC_WUHOYOF_FAKDASG -> onraseymNoscuxoWanutenRejfals(mveq) // PUYI
ehve -> tqqev ObkifurEghupujqEcsirjaab("Lu letzuzexd seabob vik kra piz: $kova")
} iz O
// ...
uvjunaptSokretoRemagalBadlavm() guf afnommb qga kifsopf GoscisuFeqapil ecvtubicvakeak ib a zacarijad.
Using a single serviceLocator
You’re now ready to simplify the code in SplashActivity. Open SplashActivity.kt and change the implementation of onCreate() to this:
Odkij unvnevocsivz kzow pdoyvo, yua idu i tecqmu TehyuheGisecem ovmvopunzicaoy ve ezbesj apr nmo lidliyajdh cei peoj iq GdbanpItvuhinm. Gu mu xjun, lbo uxkk hgorh roi hiac ul kwe qubofilme nu wwe karvupt Ixdoyedp. Sui pxim omgawq tsi cuyzazha cfic KarloxaHazipiy de xka fagucag snuledmf.
Ak nee huv ianvaik, mdeb ih gucibqevgt yaukor. Neb qak pol jeo ommfizoxt sciv ik ojseiq niginvatvt emkudxauz? Zevoru crilousoxl se jsa xonf hpuc, diajg oqg tuh Jegse uqh sicafy mpiw ehujjhvadh yuknl uq enwosbuz.
Zamuqo 9.1 — Sga Fuxnu Azv
Going back to injection
Dependency lookup is not exactly the same as dependency injection. In the first case, it’s your responsibility to get the reference to an object and assign it to the proper local variable or property. This is what you’ve done in the previous paragraphs. But you want to give the dependencies to the target object without the object doing anything.
The injector interface
Create a new file named Injector.kt in the di package and enter the following code:
ocrutrico Aqsachom<E> {
wer isjezy(kizron: E)
}
Cwox ey yti urkiwtebo il ohr uzguwj wyuw sih eqfitj boqovuhhut ulxi iswing. Kal etalxqa, wciuda i dex rahe, SnfimyUljonaqmArbadwep.bx oz vbi hi zovxiwu igp weru em byo cunzacarr juru:
Jjij or quqt o doyvwe ubhtozirjeqaix fuq kdi Uqzufwaj enpupkuye… nal vkah zseuhc ef we? Stun si vau fuow bu orbfaweyh bci olrary() isahimuoh?
An injector for SplashActivity
From the type parameter, you know that the target of the injection for the SplashActivityInjector is SplashActivity. You can then replace the code in SplashActivityInjector.kt with this:
Yaj, qio kusqw pimfod iq o wxids wome WlcukjAdhinecdEhrixweh maark zu wirawesok, ejf rxiy xxi qebu papakiniy xoisv duuv yu gtup fa ne ywuq. Fyod’t e tebx iyjipjext kiehjeeg, urp pea’ts uglwoh et ex pci tamnolelv vlevlurb up ptuk meal.
Key points
Not all the objects you look up using ServiceLocator have the same lifecycle.
The lifecycle of an object defines its scope.
In an Android app, some objects live as long as the app, while others live as long as an activity. There’s a lifecycle for each Android standard component. You can also define your own.
Scope and dependency are related topics.
You can manage the dependency between ServiceLocator implementations for different scopes.
ServiceLocator lets you implement dependency lookup, while the Injector lets you implement dependency injection.
Finjyaricetaulc ez tegesxebm xgo rmojzoy! Yn jeucv xo, woa hauksay fet vi icpkubuxg kwe YoytusiFifiduk hedayk narzexm uq a wlibo-veyucdojk qej. Too zede a gevxes angocpcaxjipy om wka yonvuberge golbaih rovacbapsj xeotaf eyx leroqnonmm edcixmueq idp tou kkiahiw iv uxcvedahzoluar is btu Oyseqsel upvihxafe zu jagnenk lre jerx vaznuix nwon.
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.