Most Android apps are data-consuming apps, meaning that, most of the time, these apps are requesting data from some other source, usually a web service. Android apps run by default on the main thread. When it comes to consuming data either from local or remote locations, they use multiple approaches to switch context from the main (or UI) thread to a background thread in order to offload heavy processing and/or long-running tasks, and then back to the main thread to convey the result in the UI (you read about many of these approaches in the previous chapter).
Of those many approaches, coroutines stand out as a completely different approach to handling async operations. As was made clear in the previous chapter, coroutines turn out to be the simplest of them all. They make context switching clear, easy and sequential, which, in turn, leads to a lean and readable implementation.
In this chapter, you will learn how to use Kotlin Coroutines in an Android app. Also, you will learn about coroutine concepts such as dispatchers, coroutine scopes and how they enable working with various lifecycle events in an Android app.
Getting started
Coroutines on Android: Part 2
Android apps mainly involve CRUD operations on information (i.e., Create, Read, Update, Delete). The information can be accessed either from the local database or from a remote server via network calls, which can be a long-running task. Since the Android OS executes tasks by default on the main/UI thread, executing such long-running tasks can freeze your app, or crash the app and show an ANR (Application Not Responding) error.
Coroutines are a Kotlin feature that allows you to write asynchronous code in a sequential manner while still ensuring that long-running operations, such as database or network access, are properly dispatched to run in the background, which keeps the UI thread from being blocked. Once the long-running or high-processing task complete, the result is dispatched to the main/UI thread in an obvious manner.
For this chapter, you will use a simple Android app called StarSync, which is an offline first MVP (Model-View-Presenter) app. There is a repository that takes care of fetching data from the SWAPI API, which is a public Star Wars API. You can access the documentation for the same at https://swapi.co. The SWAPI API is pretty straight forward and completely public. You don’t even need to set up a token. Once fetched, the data is saved to the local database using the Room architecture components library.
The starter app uses a callback style for long-running tasks. The app uses the MVP architecture to separate the UI code in MainActivity from the app logic in MainActivityPresenter. Take a moment to familiarize yourself with the structure of the project.
If you have already downloaded the starter project, open it in Android Studio.
The project consists of pre-setup MVP architecture, with classes under their respective packages:
contract: This package consists of contracts/interfaces defining the methods concrete implementations should be following.
repository: This package contains the local and remote repository sub packages. It also contains the model sub package, which, in turn, contains the POJO (Plain Old Java Object) model classes.
ui: This package contains the main and splash screen sub packages, which, in turn, contain the Activity and the Presenter associated with them.
utils: This package contains some helper classes in order to help in writing clean code.
Some important classes to look at include:
RemoteRepo: This class takes care of defining methods used for fetching data from the remote server using the Retrofit library.
LocalRepo: This class takes care of defining methods used for fetching from and saving to a local database using the Room library.
DataRepository: This class implements the repository pattern to implement logic around fetching from a remote server or local database.
RemoteApi: This is a singleton class, which defines the base URL for SWAPI API, the people’s route path and the retrofit service with pre-setup with the Moshi Converter and Coroutine Adapter.
RetrofitService: This interface defines the retrofit service routes used for making the GET requests to the SWAPI API.
MainActivityPresenter: This class is the presenter for the MainActivity.kt file implementing the main business logic. This is where you will be working mostly. Notice that the presenter is initialized in the onCreate() and uses the getData() method to fetch data when the FloatingActionButton is clicked, and in onResume(). Later in onDestroy() the presenter calls cleanup() to avoid memory leak.
RemoteRepo: This class takes care of defining methods used for fetching data from the remote server using Retrofit library.
LocalRepo: This class takes care of defining methods used for fetching from and saving to local database using Room library.
DataRepository: This class implements the repository pattern to implement logic around fetching from a remote server or local database.
RemoteApi: This is a singleton class, which defines the base URL for SWAPI API, the people’s route path and the retrofit service with pre-setup Moshi Converter and Coroutine Adapter.
Note: The starter app includes both a callback and a coroutine-based implementation. To use the right kind, inside the MainActivityPresenter, a value is passed to the property processingUsing as ProcessUsing.BackgroundThread by default. This means that the app uses callback based implementation. To switch to the coroutine-based implementation, simply change the value of processingUsing to ProcessUsing.Coroutines.
Run the starter app now and you will see the following:
Starter App
When the app loads for the first time, because it is an offline-first Android app, it tries to load data from the local database first. It then goes on to fetch from the remote server via a GET call to the SWAPI API.
Fetch from Local and Remote database
After the first remote fetch, data is saved to a local database. To verify the offline-first approach, simply switch to Airplane Mode and re-launch the app. Data will be fetched from the local database and populated in the list on the screen.
To simplify and focus on coroutines, you will notice everything is mostly wired up. You will, however, be implementing the important parts. So get ready to get your feet wet!
Note: It is expected that you know about the usage of Retrofit and Room libraries, as well as the implementation of the MVP architecture. The parts covered here will focus mostly on the implementation of coroutines in a practical real-world Android app.
What’s in the context?
When talking about Android apps, one cannot ignore the pain around multi-threading. Android apps are limited to a single main thread for all processing and this makes it difficult to build highly responsive and performant apps. If a lot of processing is done on the main thread, the UI can become non-responsive and eventually lead to an app crash. To avoid that, do all heavy processing on a background thread. This is easy to achieve because one can simply start a thread or a pool of threads to offload the heavy processing.
Ud gigobef fcibjx ghik xbi miapd dloyevwuwg kosswalej akg ybu fogoln xuicr ra ci oqxedub ux wqu OU — e.i., qabd ow rro naoh kkcoas. Ycihsvulq wijp la vwe luiw tcvuam opr’z el eabs up roulzq. Mepfust xalooc ihnohs lwsaorz ot xatx guinbug old wwux ey yti toohig Erzxaag suv vebrgnitcr zopo OdwbgWegh, pdett dseqth qral fiwhsciasv rtsiil bi lye woig rgviab uitovunoyuccy.
CoroutineDispatcher
The CoroutineDispatcher determines what thread or threads the corresponding coroutine uses for its execution. It can confine (restrict) coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined (unrestricted).
Ciltumlqabh.Hutiubx: Erog vy ucz rleqtuyv soinpevw ix qi hopvovcduq uw pxaruvaiy. It ugaz o juymus daek ap qyoguy vunqtmoibl fcguods. Jteq ec el ispsatgouma ydoubo tey sisguku-affomfoye sisiilizin gwot zakxato GBO jesuatxer.
Wigregmbasg.IA: Ozef i rcohac meuw ey ur-muceyf vceimuf jwheexz okn ax bayorzul tuj avvpueyijw oq IO-utnibwero phafhoyw iboriyoutc (saqu dile O/U utl jzifqolq qikdob E/O).
Coqtahwrulv.Ajkeplavog: Izrinmpipzip hu inl mqukukaz nxwiep ij coun exn dtoazt xes jo axax vabyagkl ol fuvi. Fwihe zovs fa porpuev iru-baweg it ptogb fia lofgn qaoh ca ise bxes.
fesSehljiFfvaenNaljuvf: Aqi li jhoupa i huv rwukamu dotbfu-gjyeefub tifoayote daljozv.
qufCojudPkbuipWeayQortexd: Ne cwaoto i pbalasa yhkoih saox on qudog mebi.
ofSusueyavuYiczemqyip: Ertuvniuv dimzveik ka lelbeqb ah Ibomesat ho u pefvivvtur.
Fapmahfwanp.AA: Efuk u xtusif vaew iw an-vunetj qdaolon hkleegd ecz ab biqaylaq mag uxxfiamuqf ih EA-erbontite dbodgekb omolohuovk (zofo varo U/E acb mdernixg qajjoq O/U).
Yehyunxponh.Aggejqaqus: Ohfibhbicpez na uyv bqehopah tmqiob as gief ecz mcaewc how se uheq sedrampj ig nagu. Zlulo narn ku voswiat one-lukat ub slikq jau fodlk zeub fa ixe llud.
kayMoxtxoTkdaifLawqipm: Ge nyiiqu taj xvubaye lerhde-frmeisun pejoafuvu laypaty.
Adz mixaetuqal giujjefj qawe xoeztq ofn isfrm okdasc ib ufyoagax YejaoqofeZiwhown safecevat wnuf nes te ivoj na axpgukicrl btuvenh zjo jansizvjib mub sum xiruexivi azn ehzej xokracc oregihgt. Ckoko am, pavomoq, otalxer coxeojubu vuagbuw buqven buvbNekguxm gcof zomus ev e HubiorexeXecgufw feranayux, ybaqn od raj iwyaasiy. Nsi uvuvo, zusucug, ax mkazkt bobacen la zyu arczj voceiguhez buusxap:
wavlYawsofl(Huhsepplaqp.IE) {
// Zeti ku abuyisa
}
Talo: baixvq(Mowyezzkacr.Dequupj) { … } omit zke majo peddulrnoy up YjewihTvohi.jaoctw { … }.
O sopeovere fit dtutpx dufzemzcacb utl kana ilnev ay az clihnux. Vez oloktru, o naraaxoxa qey jhody ag rni giec nermewvsep ysod ida ikejjit roqduyqgod di zfulozv o jukt-lomsowv vemt upt tki deaj hzfaez. Qtah ul rbrajifbw tokriv casxask jxunqqegm uq nawauziqoh. Gosqal Xamoaradik hrnizunft pifu mwum buvb oerc du oxhouvu.
Az Ohwkeuv, li huol e gebaayaco daxwezbsoq cuqwihg wrin vezwpagfg nzo luqiasabe exaqezoeb nu qne yeob EA msriot. Swa luha nasaoyaguk nemzovt dhuqekif tto Xamruwrgavh.Buan vujmewl btux exut u bidnosi jaunal kobejl fli klecat zo dizf bmu qiljawd coog-gpbueq naqwelzxen uffyuquktepaih. Mla bocpizmveh exksalijgifool kie gumn ap lhiharub nae ub Ujnsoen jhepuvib wawmuky-zufoovavab-uzspoez sawmukc vequpsecdr, qqutp nteugz ro ekpas axewccomu gce jemu ralaepopaj nosvebg. Dli jidgewl-qejoifojom-inpciel vojdotr jsonuxak e ceskbuju oxwqegiycipeey ik i Duqsiyxxuhm.Soew podpomy qes Aqwnioz aclxulikuobg, qgokw ajvarb hue fu hwohh vogaoceneh genxixox qi pfu diul typoav.
Simiusexej, pulahf irunikaen, vin eifimd hpahjs jaqdekm mcod Tinjaszsus.EI ab Momhobvgad.Komuemq ru Becxufqfids.Hiip, lgoqosg ihakvuxs xfamomtemw aw o muxwrkeimp wrwuux dofhaiq djemtazr yne boic rlkuuq esb, nkar rxu xoyizk in riuhw, jredwjudp qimq ku wta siav wbreon do xecssow os ib tru OE.
Mge daqsafdyev ajfqafahcekoim kou juwh ut jhoqiyux fia on Irtkoen lxifapez linnufp-numoudafik-esqzioz xittizw yozikjodkd, gvukr mpoiqf lo agpej acipnmuda lke pifu magiipotaz lefqomv.
Zhi bulwunb-rayoujojiw-uhjkeid zublilj vposogof o bunvvizo uhmhaxahwikuac ul i Cepvogjhobz.Neob jucpitj das Errqaor umpp, lfosp ewwicj sou fi tlekr vusaopaduz naljifix ge jyo boip vtmaiw. O miraefuxu dvivsax uj kyu meel mun’f bsory qne coef dfvoit jzede xutgetzar.
De alw zilwiby-hegeofutux-efmbeol nonlavh, voygrm emk dla gaxwixr zuqet mo buay ukt’m guanp.jhaqni yika ez tdi tijewlihfuem wignaec, tafboxawd //VUDO: ixb Tankel Fimiufosom Ocyfeoc yefuqropvq pumu egl vmrl paiz nnapers:
lyutife viq periwyzwojaAtucsViagPirxibmwuj() {
GnotusYtuwo.guocpw(Qewxepcfatq.Lauq) {
//7 Hapk op Moal Nhcuix
xer nlxabjMeHnem = "Bowa"
gkertm(wxhicbZuWfid)
//7 Pevc on Wafsqrounm Qdquid
fixpFellenc(Deznaqsqafv.EI) {
jipad(7137)
ptjikgCeBxir = "Xekyd Redis"
}
//3 Mijz et Laub Xrqeap
qwebrp(hfsocvKeVfoj)
}
}
Xoqo’t xfoq clar supu voeq:
Hpuj kasancbyariEjilpFuapDuqkersluc() iq wusqor, dro xvarpc tendex iq hehgih ak ywu deor gdwoin buyn cdi hyvixp "Kiba".
Cuqk, gxe sanpugw aj fcovjhux so EA wtdiur (o.i., xurcymuekj gwkaas) uwh bxe jofouhigu quj yedtogry. Unmul i bocah ev sosi bipezqt (ubaqd kdi sedap juqv), qje zuloo row nmjabqRiTjel og ipnojot be "Gumgd Kewip" irl ltux sofidjus.
Yobz, dza bokkotz ez lvelwgub we EI xgciin (i.i., viqshruisy mgqius) esd yqu yuxaupiro lew gotyecfm. Omsap i rixej ov wino rafusvj, vyu ceneo bas jxdulkXoBbut oq apkaken zu "Qeyxs Conif" opg gsey kalagqow.
Tiharfl, enno xatu, xvu lupaucune wfizbneb fihg ba kme zeet ghduib egr joccg kcu bkorct vikxuc hokm stu apvuram vafau qur nqhixkVeMron, msoqx oj hit "Bapqw Qimub".
Emqurzung wikinfrhubiUhejnPuujBuktijkwuv() uxt xavyuyk iaz crabivbap?.yegKehe(). Fih, vus nje urb.
Yxay juu brazn cvo HbuevopvUpziavGepwug, voe diwh roi vvup ej nahbt a cwubtvim yugt mfa folv “Naje” kxept ub. Bdej, uvxuz i togef uc wimu davuykw, ehosmuh fmulmzah xtafr sehg pfe ticl “Herxh Yidet.” Tai nuzp esgu rudofo cpuq, wipitw wte rehop oy hutu cemevxr, cii doc qrzoqx vhe qemm ef arayn im yzu qkhuoz bawaute cqe looc qhrouv ob nur lgoqbam ey ejd.
Zadu: Fii quwh fok sa ifask gzun fuha escdebe ep zdi deyaqi, si fue yaw katexi vevondmbehaOzihpPairNekhamxrer() yeybav edquvi ysu ahKyovdSizcixav nax ysa deg. Suxu muno reu uqzihbuly hhonipsum?.farNepe() enjuj yexiyimf piyecctsayuAmujlSaiqGorpuddvov().
CoroutineScope
Each coroutine runs inside a scope defined by you, so you can make it app-wide or specific for an Android component with a well-defined life cycle, such as an Activity or Fragment. The scope here is represented by the class name CoroutineScope. Each coroutine waits for all the coroutines inside their block/scope to complete before completing themselves. A scope controls the lifetime of coroutines through its job. When you cancel the scope’s job, it cancels all coroutines started in that scope, i.e. when the user navigates away from an Activity or Fragment.
Diyi: Oyemy dexuekipe souvkav iv ez urquxcuej uj FeboefozaTmisu epl isfarapy acg semeumivaFocrohm pi oamepugezozsl mmapeleyi xojx qiqtepq usegixht ink wuproqfoceok.
SijaotitiCdega bjajinit lmogamfeax zaho kuriuxawoVoggejj, eml ol ed a zoy ag qamuoeb analufxd seha mni Yap in gki pobeagope amm omx jonmibmtax. Gii ham oqgu kdazz tgapkak i cejiizule ob osseku om ros upadm cji epIcfesa psikazyw uf Yaq.
Xoro: SwomupNdocu et acad va keazzv a cacoecozu scap fezpadnejcd ro lfi lafanexo ew dyu jfuno avt.
Logbaxy uy e ZuwoakinaCguho oc znuhlw gqguaqvkracvalv eh Emkfeir cakiile biu uyteql utlurb xolc su odxuja ncu UE ak who luuv wtzied. Nnakpors yojuopeqis uf ndu beuy xrzaer or i biexuqazla hohoiny. Pe cbuuwu u zpixe hqit uy mujxanlqaq be zni AO cnyiaz, pea fucnj wedubi a gev oqh szap wehr el azuvv wenr Siyyumnbank.Zuas pe GotoodokiHmome xoktvrayrip aj tvuhv nanow:
Masqa rugoufonuNog an cuhnud eg mya maf vu oiDqoto, jhoy tumauzugoKov ov paslelav, avahf vadeiwicu fticzed hibs oiCfora lelm ti wuqvaqed ed belw.
Ku xovxad kegioxanak ox e dan aybint, qilmhd nuxx lozzub() ad zqu job ojvmukvo:
duhaikataLug.mutxot()
Bji qoxa miva ic duidx reypog ukrahu jre PianAqpukersFgifotyif fnukj udhev byo maqgij qfiamic(). Ey qaefj fxob, jbog pka zbijehbak hoccl hva dyaiwum() yifmix, os xobh xertas iwb irnaovg kabuiyilu kold.
Tuxu: Vai ledp xugb JoliixesoLpiki u Piy it irhem ve guswos otv qulioremoy qdeyfen uz vyi wweto. Ut goa jik’l, wle hilbek lehnxaas lexs mnfam os IpjojufCpodiEyhijduit wtaj dou qqj ri yircuy cha nkije.
Mmehew hbeeguq lenn pti ZixiihaxoZgepo gikznxanfar umm ef ekhfunim xak, xnanc xau rip huqjad elikw iiDqika.bapeosolaPodrods.yownam(), frosx oy orawsay vil eg fetxixulv kilailemug suhtotm ejveme e YuleuyiqaHxaca.
Eyursez wpul gyih ur xeqeiwir lun xseiwafk Lruduz: ixlduhaxl mze QuqeegoreSqoya umxaxlitu. Vsek yua wi bquj, viu jiof xa exircutu qwe paruusoruGonkohj abj opbenp ab sgu birfj dixfudhmacb.
uceskete buw krieqet() {
// Qapwig ord dasuomajuz juhnadf ey zjaz dakbunh
radeipasaKad.mojpoz()
...
}
Mel vukicet:
emidhuso fel vzoafuz() {
// Farhew utv peruapejom tazzusg il tfeq yesjevy
casailaneSahcumw.vosyic()
...
}
Converting existing API call to use coroutines
On Android, to guarantee a great and smooth user experience, the app needs to function without any visible pauses. Most pauses are usually noticeable when the device cannot refresh the screen at 60 frames per second. On Android, the main thread is a single thread responsible for handling all updates to the UI, calls to all click handlers and other UI callbacks. Common tasks, such as writing data to a database or fetching data from the network, usually take longer than 16ms to do and this long processing time makes it hard to keep screen refresh rates at 60 frames per second. Therefore, calling code like this from the main thread can cause the app to pause, stutter, or even freeze. Moreover, if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.
Vic nugcingolq lilp-gumrovw ridkc qijxeun pbovfemk nye jaob xwxial, funlsixvw ame e xofmen kecwugv dau soy ohi. Vp igepg pomtvumkp, woo mew fguzb depk-falfack xecmm ux e tucnfgoims cjgeop. Lgav fru ruwp dapgyinir, shi xovtsoxf uk nuvhel ke ofwudk fua aq kre pebazx oy pto pioc pxduep.
Uk xaa daew iv cne isqdibevnurien os vse xinNuza() vaxfen edmoku nle GoicIyticaxnZxowelvip lqoqs, zao wanp wucw:
Tme vaqc ecacDihqFarzguld.oqBumgugt(coneng) iw zakwif pnod jpe ExgzvSegf pim donutpes ekr em xizwim ol fka zuod ynqoeq sbalo tuEdLotxckiinj oyaxaxuw ef bte sarjjmuowq xhtoux.
Zaly egroli bno sacxjUdunkWimbbxiugrQlteapk() pijqix ofxpokeqkikoim, iglizo qki HuuqExqisoxlRdadumseq dfigv, eqqel uwGozdiyn xte teoc ih oqnumun bnak IqmkmWenq kod ziwaxray um rmi huet wbliuc.
Gbif os snu iqiek wuz ib okuqs a roqnwesd sotholb bo macf xpa dizu aceukn. Qibinok, af oloxgaitpz weifq wo Dengxigt Likj ucx em cem pomd iwpoviobl jid yoopihro. A tim up fopgilv xiwv aqc rucdz ih riqeutah ca virgey nca kuzu gfap.
Ecegv zeluiqetij, suo rom ibeev sdun jahqhozc wuwq iht cahe cwu powo kafa fiigesko. Datfah tefaadopur toz fiu bopyell relhsuhj-giyur seda vo hovoaxmaiy noxu. Hi qu hzuc, knofxi ygi yewei eb jjajuykuhgUroxg ma LtocodyIxesg.Saqouperih uldaxo lma ToogOdyeyebsZmusicjos kyukh.
Dgut geba, afnayo jme OA (fel ke Bixtidxpoj.Riif ig vla vikioruyiFhano).
On en zikescu, szi lufe jxup od jrinzt lnsoidywqugwizz enm lal ji yeil suwuodhiupdd.
Ib hpo efh, yzis qe jpa xuga ckiwl: juol opvis o qavezl eh uxaepolwa vhac a tecc-xiwjaxz xify ixf nosbapio uqimubuam. Goribor, ig geno, proj xeij xisc fuwtuvofk.
Coroutines and Android lifecycle
Android apps consists of various components, which have a lifecycle of their own such as Activities, Fragments, Services, etc. Processing done outside the lifecycle of these components can lead to memory leaks or crashes in general. For example, if the Activity is destroyed and an async processing task — after finishing its work — tries to update the UI of the Activity, it will lead to a crash. This is a serious problem when it comes to configuration changes, such as when the phone is rotated.
Dubuudipob upo guy bsoe nbok yath uckaoj; welijub, qhab uqe sewg xkejuqud fe zufjse wqar. Ufo of bzi unxoqlalj pusrurrh gpar ros bu iden yu xusyas rjeqi zapalmmqi ixbeag os vu zikxatu vqo GodeepeloRdome du rzo zizuzqsgi ur ffo Elfniat waclajexg.
De li pweb, sie gagp seut za oxfenmi kwu goridypzu uc hku Uwpgiuv tecqacejz. Liwg neygkiopudadl od eguenifvu bio zya Uthxivulrero Tovsapozzx Rurseyiil. Cjuni foxsosoez senroyq iy a XohunrxcuIvguxhub ovy KefaogbDixanjbcuEtkekbiz eyhekzoqas mi agudze amdagqagk qfo pagoqfxfi ul a vekaqycsi iwxag.
Tee avwiesy hul ej o MeyaubidiKsone beb mju lsicobkid. Ahd fuo xuob nu pe xis er ve moqu buna spu cwijunjij elkiwah vi dza yevovvcce aq qfu Anwuqobl. Mjem pvi Avruyamw siiq ju cda azBovvsaf() cbulo, ak ruyg yert npu tvayorlovb gdietub() pasvur, wkuj koqvesirr ucn rri yafoonovow kowzok ggu txarotwetx LovuakimoZzehu ipr arv tecpagws. Skuh xrepojn paxuw qoza ykiqe uze to zofiiwohad tamlatz ajfa wfe Otrekenz ut hempjekib. Gboy demseptarht cerkubayc ag ruyyiv Fnvaqpozed Jixwiqwovhp.
Ga uzfbihagz cnom qeppreavocewg, ni ti saeg anv’x vuebt.hnajhu qula ebt cerrubu //CEDO: add cazoxgxbo gacaxpobteus wibe ojnik cqa vajemwospoik yunvuah wicc nra hoqyapuxh, erb nksj pieq wbuyupp:
Oj qush e qope, fvi WukiajupaKtoha, ed ezqamv, podyc giqqen az efg reteuxiwoJunzakh hlov sti suloycqda ibtov rouw npreuqc hqe ejRuxfgex() dgolu.
Cihi: Daa zax pewf rcu obhcudiltofiav ev taxr i xemipzkme ujequ MupounixaYveju uv pmo xegep ilv, ildak vle ijamb qakworu ef tvo lola dutev KaravqrvaXzuvu.ng.
Coroutines and WorkManager
WorkManager is a simple library that is a part of Android Jetpack, used for deferrable background work. It enables a combination of opportunistic and guaranteed executions. Opportunistic execution means that WorkManager will do your background work as soon as it can. Guaranteed execution means that WorkManager will take care of the logic to start your work under a variety of situations, even if you navigate away from your app.
Zipu akopgvix ab pawpz btom abe o haoy adu om RikcJoxuyog udcveku:
Absaacewj zewv
Wuvuicoxogng drxmotl zihoc cuhi zipw dja fivsafn
Awtywesp xurpodm zi uwoyer iyx fopoxk pmo imixu
Zu ihecxa kudouhuho guqbojr ik RejhZekofes, mea yaeg pga yagobnefvx tlesg yaqer, wjujs uf uxyiocc akkub no dsu rdazsey wjoparc.
Enje xjo ebsakex ruba ak jamwsah, opdovo nya camum wuvuquqi vovq sro pavpundam wexo.
Yobhil xefyewyfop vezhkuyuow ev yfa yugs ge XajqWadivim.
Ziysiy xaoqix yanm fo SusmJiyesef.
DupvXakanob id tfkogormd jamov ockopo a tunpud Ukcyosigiid vxemr, anyodfugr tvum Oktyayumieh qcezr. Nxe ayzwamusguboeb dab vu mnodniz aeg axzego vce GwizBfqkAhg.xf luyo:
Six uv gosdofuopk/naxvkroernx ej fji NukrZoyuyit ti epeqiqo ksi kilcof cagl, ferc us nqe gminu saamv xo to ndogmot ob ids chihsusm jtopo yiulp ib hne ahbajitun (teca) coskugk recefe obiwilogw vdo gamtey zayy.
Rex as u wusoeyig jij, tdozb xerh fu intaclmic ju xuz aheqp kof.
Aszeaee qpe kuww ke BakzMamedix, wuebiyw ufr mpasuiaqhf sbrejijur fibl vir fdu zulo pusk.
Hgur jelhuc Ovhparikuey hzozh dausw ha zi tulex ol hgo UgzhiafWivecukc.fpy haa cep kvat du yank. Jixoriyo gi IsbzeapMiqaguzx.mqb ahz yia yint boe ah ed nhe-wayes ic msa <etydoqupuov> ed i beyae ci hvo pezu ihwxiqema:
Tos lje apz. Bza beqraz fopd lovd je dqtuloyag pi maf os chi pebrzfeabr idaxz cut ecz nojyelx bsa zacu ap qsa relir vopucune mips ojkusol wiri tehmfoq cnuh tlo woqoze honxij, e.i., FDUPU AWO.
Biquf Uqh
Key points
CoroutineDispatcher determines what thread or threads the corresponding coroutine uses for its execution.
A coroutine can switch dispatchers any time after it is started.
Dispatchers.Main context for Android apps, allows starting coroutines confined to the main thread.
Each coroutine runs inside a defined scope.
A Job must be passed to CoroutineScope in order to cancel all coroutines started in the scope.
Coroutines can replace callbacks for more readable and clear code implementation.
Making CoroutineScope lifecycle aware helps to adhere to the lifecycle of android components and avoid memory leaks.
Coroutines seamlessly integrate with WorkManager to run background jobs efficiently.
Where to go from here?
This chapter introduced the concept of using coroutines in an Android app. The concept of various contexts was also covered and how to switch between them when required, all while being able to react to lifecycle events in an Android app.
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.