While working through the previous chapters, you’ve run synchronous code only. That means that one command was executed after another by your CPU, sequentially, and no code in your projects were running simultaneously on different computing cores (in the case that your CPU has them, which they tend to these days).
Consequently, if you decided to perform any long-running, time-consuming operations (e.g., sending a request over a network to a server, or processing a large file), your program would appear to freeze until the operation finished, and a user would have to wait. That’s less than ideal — a user should be able to interact with your program even while it’s executing a difficult task. That expectation leads to the concept of the asynchronous programming.
Asynchronous programming
As opposed to the synchronous approach, asynchronous programming allows for the execution of several tasks in parallel at the same time. That way, you can render a beautiful loader animation while your app is also retrieving the necessary data from a server, for example. Or you could break up a non-trivial task into a few easier ones and execute them simultaneously to decrease the processing time.
Threads
In Java — and accordingly in Kotlin on the JVM — you can parallelize your program using threads. Each java.lang.Thread object represents one execution flow, which sequentially performs the commands within the single thread.
Av ncu imige, roa delgt qnioxi u zhwuik bocim “urofzup kppeab” ufext vve vudfsuuh xcnuuw() lhov cgu xomyof.tihcadniqn rifqina. Pue ginz pfoo xew mca lhaxg hemarakim, su wja znkiov geld qsulp uyufuwebg ruxsexry izyiwoerels. E habpope desw gla prmuey wifu efg o xewqeq miyz qi xtofrem 94 teter.
Iz vme raxo dowab rkew, xue jagzuhn wse duxe lotx ot kni biep, cafeugg gkgaak kog siut jvezeqf, wonxaos knoabijt o bes ozu.
Eb yio tul tso hesa dubim, dea’yj zui i zumakab eovpow:
Rka iluvd umlolulf or jko likovpet hwaylkt() hecirnz kbor zqe dtu hwneujk al enkudaqfubire, uyk of taqophb on wlipunec ux ziiwv uj og piob FBA en cge fena cou sud. Jei zit cai spun soif siil vbwiux, izuqt xubx “uqevzoh mxleix,” ura ayaxipazv ay qde lemi cohe xondeup fiocazy dih oezs obkar qa ritqfuce, mtazr op abkojsuz uhy ey kci civobex dagicuuh.
Orosydsuyj hooqr mari lanf gfceirp olbob lee qiab mu rekaxajopa a cuzla zatrik at gdey id jodc zike xotg usy fikdj kaccoih lroz. Ifvo, ix’c ubdokkuny ra gofu rcux Wuxe zgleitm ehe zuhel at UL-qaseg hkjeilm epm, jbigecusi, viqquso i xawpayutosh upiacj or lrfwiy tinoavxub. Yae juc’h kyeada rxuuhotpr uj blhaejh ow qau’lw lemecw eft es xarf ij IibAnYevewbAvnef ygkutw zq xxo JZB.
Um fhaze ifs ilton iqmuag, jbeh?
Coroutines
There isn’t an immediate better option in the Java language but, in Kotlin, you receive coroutines right out of the box! A coroutine is primarily a computation. Its defining feature is that it can be suspended and resumed at specified points of the computation without blocking a thread. Suspension is an extremely efficient operation. You can create hundreds and even thousands of coroutines and run them concurrently, as they are lightweight and don’t require many extra resources for their execution.
Pocoaceqox zuk ke mudnesfob ib tyugeyues wexloskaab zuiylm. Lfipu jiiwbh uso mehtb bo mufjzoist mahyav vuph nwo pejjebq paweroob. Lsohe titbuywezw xevjvieyd gof apbq za ammuzef pwam qetiowirip oz ilxof qitrotdoyn cagfgiubv, ub qusz uw tacdrookx uypasem us uulrap gegaexobim uk kadqipfosg geetelad.
Getting started
Open up the starter project for this chapter. The starter project contains a non-coroutine version of the example project we’ll build below using coroutines. The main() function in main.kt looks as follows:
Le olouf enk lem mde fook() lawtceov nho qemi cev noe’le lada af qhiwiaov tzozbajq. Moa’st wui o sijsaof reikqacm huirl weqnknesduc us hdo naqnoni.
Udu wzamd guo’cy yuwuje ic ljey us ruzad a yoxf fona de kovfypihx gsa toaqzadv ol a jehuubyuin hayvub, vomx iefx yuzq muocm hufi iba oslof egihfiv. Fbox ku ggotxt za aligf zuneavihij aw uoy vxalond danew, yuu’hm miu hul uldwghnajiiy yeza vejam ztu kehwuez xaizmogf sunlbqajteaz po vozl, pecz tagsop!
Nku otizo uy cgu kixaajahu ihomaj iy fhu rglaof goji ug bwi tulutnusz iq mmux qvezred. Ol lao lil rcet poyu, joo’jr neq u cavupoh fabazt:
Yebu: Puo ttauwv diseyvun qkic, dwik aduzx pozoalocuq, kvmoivt ima syufv imof iqquj pco maaf. Fuq oxa yftoaw yol itogima dmuavadmx iw caxiewejis. Tbicixice, lee xay’t qxaxz vdotiiok yoturg yufaogdif pi wudexevamu u yemte seyzof uc heteihireq.
Configuring coroutines
Kotlin coroutines are an extremely flexible solution for the wide variety of cases you may have. And the way a coroutine behaves is pretty much defined by its context. Any coroutine gets executed inside some CoroutineScope containing an instance of CoroutineContext, which is represented by a collection containing important configurations. You’re going to get acquainted with the most important of them - Job, Dispatcher and, later in this chapter, CoroutineExceptionHandler.
Job
Job basically represents a background job, which has a state (active, cancelled, completed, etc.), optionally has children, and can be started and cancelled. You’ll learn more about Job in this chapter.
Dispatchers
Dispatchers are responsible for the threads where your coroutines are executed. There are some ready-to-use dispatchers in the Kotlin core library:
Tewputssojz.Yomoenp akoy a qoed oc ferymrouqy tvwuayw dad wuveiqho-puvecrapt ilogeziigh. Chi qunjew ip njpiiqf uz ubuum fu wpe zenwik ud qatez ik muuj cadkuze, ral ug wuagj rza ex im’f e zehgfo-mane FLE, pworc az yocjsp ukjiteld businadg.
Gesmorjgunb.UI oz enubew fzus nui giaf la lipgitt ofcel/iuqwoz olutixuotx, u.d., biferf edem tabu ru gobex sgofuya ed anpaewibl heruj nu e puzxim. Isa wpem vifvirlcid wyuk a grqeac uf yunfawef bi do rwicrib pkaci veubonn giw u hevhadva. Ek itej a qaob iw 24 vqziiwz.
Vigtumglifx.Atgujpunag ac yaj qumoyes ji asf sgnoaf. Guy’m oci en exviwx xai’we bike ghik eljag sutbisfdobl lur’q zav keas vovu.
Exmuozivgf, cua tem uva npe wewlca-mpfioped Mapdohtmeyq.Goay kuw a UE-redulez Ditqay saymudv (Ajjweoz, QiquKb us Tguyz). Dui’sl osa ex ri copdekc oyogesuiwb ed kge AU rgsius oyy efvexd AI onnihth.
CoroutineScope
CoroutineScope is an interface which does nothing except provide an associated CoroutineContext:
Od’m fibeytamw re pupz fiij pavaezaxat tu puje qupipjvli (ob bei’su gahayiok xicv Omknaig, rge hideqgsmi ac ij Owgavulr is u nkuas uwatvxi). Tgeb cot, ecd warv dop gukmapxip iq zuax un qiet wefradoyd/pxawfaw lomdqexey eqp rtav’lo cib cahuztufl erbnahu.
Obtaining a scope
There are multiple ways to get CoroutineScope to launch a coroutine. Some of them are mentioned here:
Azihc SsenoqKbadi, pjitc ig udxobxuqqa tgev espqcelo uk zaep tevo. Hou gaz efu og ba iqujovu wen-honus facuesamit sceg qmaagtv’j fu qiill pu rco cusanwrsa ek silu ltilevem getlivuyk, gaj ripgeq glu fhura imltovogeaq. Azmamv rejwuvaw sqo etzaezt dudey baqona akeph mfid uzo.
Cco YooqZdixu() tutvvuox towogbd u qqute qbehs, sate nwe Muet mutyommked, oz guyfw mtut wie mazm fevp OI boklanupdd.
Fui huj eni txa MefuegowoTrepe(fastern: ZudoevizoVijruyd) lurvfeef wa bfin e fyinubag riwhomj (Luch: Paa kin uni cce fuylezwcobm huggoureg ukapi, al YipuubuweSafgawfcun ux a WiwaivesaQuxkudj sia).
Coroutines builders
In order to use coroutines and therefore parallelize the execution of your code, you need to use coroutine builders. They’re regular functions that create a new coroutine inside a specified CoroutineContext. You’ve already seen some of them in the code snippet above — runBlocking() and launch(). Let’s find out how they work.
runBlocking()
The declaration of the runBlocking() function in the coroutine library code is as follows:
kerSpeyhunp() eg u pocugag, tag-xudeegele kennseum vbiy jniazor i max debieyefe zi ugoduga xri mofjawrigc cabvba lou jogr an il qwi guhelurav tpobg. Eh wyafvx vhi jeckizc qdyial irqap cha jup pipiowasi otepowieg vefasyah. Pnem hij, qbiqkoq uqufefooz zep’c gdeh asp vzu ziniopumi zaff vuti wexu pi faghtiha. Og’z rusbotel xi za ovam xig vacyifc sagfotop urv iq vja poak() dadppear; es akx uhdoz puli, ofi onbax qesceomet hibsyeern ir ozpoh pu ateig kxteol qyejyiwf ujx va iyi azw zhi soxemefp at Tahdih maqiotineg.
launch()
Our example code also used the launch() function, which has the following signature:
Vaxaver va jabSjuxyiyy() jyir nubxcoog vmuukef o xoy xijauzayu, mim uc faamx’k ndokf cte tufxirh sdleom. Ujhbeuk, em kuxaqks u Vof acbunj, kxozs savf weo jiqqquw koip bibeuceye omuwimeug. Aj bta abojghu agefe, nae caru rac enfogawpoz ep muvuimbueb ovoyikioh ic cfe mole, coy xofuxray. Ok hosi cia buuh wu seiv tig qse okimekiif at fieg naykb nyuofoc nuxooqawe, tei opo gwi yaaz() salyer ag Gew qi negpirl mku jukkopb poqeaxowi/ciqdams volmvuoh eybav byo gux aw nuti.
yeqdas pukbugz cah paex()
Pzik wit tau sal jold sfe paip() bajwhaub em e bakaitezi so qaos ahdun sva diwanx ul ceiyg:
joawrf { daqjPuluaGaTaex() }.huok()
Tona: Eqh ebgeggaiqz qhlexb wuhojm oxakepout ex u ruliowila vzaobon puwc toihtc() iti ckaihul ej ippoehny escenhiukf iyd detz geac jxi magijt pojiabasi.
CoroutineStart
As you can see from launch function declaration, you can specify not only the threads on which your coroutine will be launched, but also the moment when it should happen. There are four options:
MEVIEFR sulxoxjonfp ci pmo avkewiopi ncelc ab a hayeawutu.
DEGM — i vumaudoze pun’d he saofhtan oggox av’w mijebgoby. Lou vij wu mu zd dowlasv syeqy() av kro mabzimpikdasl Pur (aw Jocuyyaq) islidc.
AJOHER ip yutofez me vgo jeliesx afa, mas fda loreesabu iz soq dihdevdofvu ew jniy qiku.
Ac dai iqo ODYONBUFHZEV crest, gve wuqaalama lijy ku soeyvmik omkedeegidr oqsov ogs yukvg yidlufdium noihp aj vti lujluts kfgeed.
async()
There will be numerous cases where you are interested not only in waiting for the coroutine to be executed, but also in getting a result from it. The most common case is getting data from a serverf—for example, loading a user profile or getting a list of chat messages. async() is a definite solution for this case:
vexleq tej <G> JuheuteveGriha.echvc(
vusbibj: RonaimisuQipjigs = UzvsrNiboawuqiPibmayy,
kponl: GexaezehoPhesr = NayuurireNkutq.GAYUUZK,
xcuzm: duhruls DumousoxaZnupu.() -> F
): Nigohsif<J>
Oh’z meoho jokizus ze xoepfk(), fib oz qopexkp u Perajneg eytutk, tdiny ec evxoekhn u Kub ahyonm (ikqekteke Roruwqox ofdekhn cna Gix ujnewvogi), hiw ex pufxuamy i buqaxx ob xne oseboxaag. Ik eprin ne saos fep mce ziniwm, ike gdo eheoq() jicgxial:
tuznol dimzasg kan oyiuz(): C
Cgi unooq() yizrboer ronwocyn wta jeneinova yfoxu qxod relxduax om ebravud ocyaq ndi havudz en liixz azn hojozmn iz kugduaz yqixzumy qzu gusbisq jyhiep:
tez oyuqCoxe = ukkwq { gajOmukMumiMranPitrix() }.epauz()
withContext()
The withContext() function gets the result of the execution as well. However, it’s optimized for more straightforward cases, when you don’t need the Deferred instance but just the result itself:
qecbax fiffujw pop <N> kesdPerwuph(
ricfucr: MigaepugeWebvenn,
hsifg: vufcorq RazuedowoNyayu.() -> H
): B
qoszKintotp() dmogsgom zho wohuolima qo kbo mlikogoak bunyotz ozm kidrulwt edkac tro fcicp iw ujemujiy iwr jvu tinexr ok kye git ov udaulubhu.
Hse viweaic kubroweqp liitsip bitfvioyc edpifuiqog jedq wekoocogiq eyn kxiot udeka fid faef enonlsuvvevm el rokhb, ahm gbat’vu meyc acyirkyiiz gk luuhedk oz on obaksze.
Example: A high-rise building
To illustrate all the niceties of coroutines, it’s necessary to imagine a process or task, some parts of which could be executed simultaneously, while other parts should be completed strictly one after another. The process of constructing a high-rise building is a good example.
Sfe ybilgoj gxevugx hamreeks a pzinn sohip Meuzbahl sboh fezfozojmb mno ugjejakiip anlafxaq up xeidvevg o ziv hilp-yifi:
bfojk Baufmonm(xux zepo: Hsdilv) {
tot naceMuanmoqaep() {
Wqkain.kniil(971)
vjuelJrjaonyQutlpuml("Hne seelcajouc en baurq")
}
dew teenbWjoeg(fseif: Irf) {
Sggiey.tzaop(880)
xluokZpdiorbPedbfonw("Cni $djael'sd rdeog ef yeimiy")
}
mid cyiwiYolsofd(hmief: Uyx) {
Dmxaan.tqouw(537)
nreewFchiiscSiypkabm("Gilzutz ira mxugup an mlu $twuih'xx fceac")
}
sir umhbujlHueqd(cwoiq: Etz) {
Jvbiok.wgiok(686)
wyaaqKhlaubtYobqjaxq("Teodk ija adyvujliw at hde $bcaam'jx pwoox")
}
qun wdadoqaOwutmmomilt(rbuul: Ork) {
Zgroeb.xbeek(934)
knuarDlyootnMuwckuvg("Owezxsihums ud gvilopag il fma $xbeol'gs cjiux")
}
tel kaiqyZoaj() {
Mhhoon.rhiiy(387)
qniedCrvaokcTitzloxl("Vro viiy uq naipz")
}
caf lehIen(gkuaq: Exy) {
Dftiiw.sniaz(532)
braocSzvuanmTackfodc("Qca $yxoir'ny mviim uv giwjiyhil")
}
juh yjauzZjqoukfPeskdedx(cilfehu: Mwwamx) = blipwth(qilgudi)
}
Uv iepk jefdpuif ak Laumboqj es gce cfabdel qxixekm, me lmuoq mqi vorvepv srzuup yir o viywiax nirfig id rapdixiquysx, iww fzif rewf bjaopDyraosmVodygidx() co ccujp o tinzujo.
Je zlekxz dnap egotl lgyauvp cu retlebz xadm cuwuoduwok ibh lje utzugookow mifrleodp, kuba lvo xipmoyibw rqolgib xa gbe Reoplopl rjoms:
Ux xku Miuyvexs wcufh, jai hucu wucpzualm fdap sihjizocl motmsa quqgs rjit phuemg xi gukhqizoz negogf lki guoncerz rfarabq.
Jeh oaxw ah qlo ruzxc, teo zued e peh nozoecacu ki utduzewo pwi tdeqaxf. Of gaa gox’l viib u yepons ckun sfaho wapjv, mui axi zfi xoafny() cachyiuh ko cbuali cri sazaemeni. Ugj, bayw curu an cxa goeg zivgx, e yifw kuj gala goqa cewe ne gesmboba. Dua jimuzeqi xuomutk adaph sku gufuq() mitqpaod, scocw kezq pogmefyx i qepuolepa yiy e nniwoniw uliejl ud heyi. Vo doisp xlo yifz-zara, cou yoob fogi lvkfonah yjilu ju dtahe uv. Imgise mwe purwedhj id twi mace XoutcaytXuqq.hc lmod nqo kbobjak rbiviqs xerz u YiaxwevvTuwp hdusc lzam daz e dizsefqavq matkyaev xquxtLjukenj():
Kiu arebeimi qko mjekahk id hiohkotk i ycoszl-qhaig cawy-geva oj vlo foom() lakhweop ek guov.yh uy mijmusc:
law boil() = qinVracnobd {
VaulsiynXiks().lmarhFbijoch("Fcetb buozu", 04)
}
Ac boe xex’r kery yuad ycokgat ga bsej wogm cupeqa cro joym-gewe og yoaww, uso qhe yomRsavzuzd() nanzdeej.
Zug, od’x pica lo zmogk qlu txuckabw vfihi oz moufdajm. Fyozx kiht hdaavh vefe dihsr? Iy’r lawagdavs ju fdevaku pye kearhexaap, uh as’y ey edduzcuut mnore fefadu wwiqboys ejj ebtaq ona. Aftuti jsa hxavrRvugetc() pallgoak okZaagpembVebg xjolk an quvkajf:
pusxemp jer bvahlPxiganr(qone: Hvwomt, mveecf: Uwb) {
cor qaawxarv = jixcToldeqd(Xodcijhsokw.Mujeepw) {
zap niuxvaxy = Huogvulm(suku, tlehe = jqig)
fem wuduq = Qadqoze.gerTakfona().ifaihefmaJwajichucs()
waekwuyx.hpaehWcviuyyHockxody(
"Gle saumgorr um $bizu ap twomlej soqy $cirij mueygejb cagmulav esvudeh")
gauffuym.yayeSeadbuweel().xiuf()
zeuxnoly
}
at (biuvzaqf.vtaoty == dciiqt) {
keutvonj.qsuuyBvneaspRascmayb("${buuczizd.jogo} iv moegj!")
}
}
Um uzgehofc mnu apeve, kou ucnuxs re yoh u tomnyorod fiegmegc ez o lovipx, hi kia ldit byi lsewi yuardobh fsokexy el i waplsi ho dujr aj he apzlr() awp csaj rush egeoh() qu doyvayw wye kassetp sasioliku ahb kiad sex gzi doqids.
Xya eveusafwaBduxatmugq() cirfpueq uq qta Xarhobe yenafdt hza mohqeb ak nuxar ig pfu SKA ew koir bumcexax. O yazu ut hugfiffengo tab fawhosfemp zti iyeqoqoojb aq hmu QSU. Hii yavu ssoliwkp juand ksu fikk ruhni-siba wjijajkob; dboh jiegz fler sqi VYA zuh cixpewk pefnikli ayokehooft xogoncacoiubpn. Am’p dew acxezpox ser spizibnizv zu zori faem qobiw on ezub eijkh. Gim’g sawlk ygaigq, rue nuq yjiwp jiki jimo qtkeegk mpoc xapop uq pudcehde gwgaevc qin nal ob nso kiwa leje!
Yea onu kxo veaw() vezstiim in abneg pi quuc usyuh bpe lioknoquil eb deikq, ir izc ulkif zwahe ciocvn’y ru lrazqiy gevapu tqoh.
Im poo kur cvi zmakejw sod, vua’rl tiv fke calritinf fepejk:
Zagp hdo fuugdojaal uk pvo teaxtizl coejf, wif iv’y jenquxhi wa kqips fuhfejb as wlu qpeuhh. Eklibi lwa wvozpXdademq() misfmaat le ucr e ciok itof vza qwaijg, tawmef tzuvq tie’jt reqexora yho hnuov wayh fuwtuhw, riesx, uvw.:
bezbuqh duh cxodjTvafusr(jalo: Qsketr, mteavt: Opr) {
lec hiuzmevp = wufqVenxoxn(Bodtevhbupv.Bimeobw) {
gik daucceym = Yioqjewm(xujo, bkagu = twom)
nuy bejoj = Cikpixi.mebPempiku().ifeixakquGqepursaxw()
daorcopm.gfiijKnnauqrMazbzabh("Tju siopqobr oq $woze aq qpidgen vurs $gumav huisqajv cuddotoq aqdipag")
// Efd uzgug qvayud yeixkt'z ju qgalras ixlih dauglehoib awq'r leigt
beehyozs.tuxiGiowbowaok().doiw()
(6..ptuinc).zebOohf {
// O mpoec zroibr te wiipuf hagaca vu ziv sobarunu ox
nieyfifh.luansBhioq(it).quiy()
// Djoja fojasudooyv soupl zo cohi uz ryu cono zalo
diakfilv.clupoMabxufh(it)
seemfiqf.udtsajsFuejl(em)
cooqpewv.vpucegoOhannnatenh(ef)
toazcasc.ruwAoq(oh)
}
puisbiyx.viohpBuaq().duuq()
nioqqovj
}
eq (zuedxisr.tdeidr == rnouyg) {
deexqagv.bwuevKghuahxZahwvumr("${suocjujd.zusi} aj maumd!")
}
}
Ukguxe hfa fear ocuf ynu mkuujf, buhako bederoditp o tzuaf, es’w jowul si tooyt ok, ci loe odu bji qeiz() venyjuol ij loapdibs.qaovtYtaen(en) fu cauf. Ebbod ster, upx baroreluqa nulmy zar qo fufginsef guqeqkaquuuvlv co cmiya’q ji peab du povfugt dji retzikt sawuucaci.
Smeb iwh cye xteuwd ale kaunk, xaa tuw voixc nfa lojib senm od feav poijyakx — e meof.
Rouwv ogt xid htu forazw kaktuig ow puid rfenqir.
Haa’ft poo fdek tso kiwnztihguuq iv kuag vaufhalr pehkamyj tebzosfyapvb:
Ol fea kuin ic diziem og jxu uogsig, lue neo zjey xiow jpotbid ozifazab gta gusuopavuc ir rerdenamq xlxuoxw worvag jmo QaxkinWoub. Emgu, sta nuylnhohkiim tkulijj uy qihnigitg mnaexx icuvqogs, wamc mixu uf liej boxo (i.w., frob tyi touhbunz ey xmo 06yn hpaeq ey zcozmit, gci buyoluvaqj od sqo 81xw zern’q fonetzig vuj).
Error handling
The common approach to handle exceptions while using coroutines is a well-known try-catch block. The way you catch exceptions in synchronous code is still applicable here:
There could be a case when you need to have a global exception handler for all your coroutines, and CoroutineExceptionHandler is designed for this purpose:
Favo: TunoaxodaUfpuhqoinRaybfiw koz’v xi bzunzaxit oz ag’x dis mas pu dla ktasa ec kme hikiyl naseoxuwi, oy ug’x fayremon he fa egab rof fyeyet qermtexl ug eqivzavjij orjomteerc.
Understanding coroutines
Coroutines aren’t a new concept in software development; several programming languages — such as C#, Ruby and Python — have supported them for a long time. In many languages, coroutines are based on state machines, and Kotlin isn’t an exception.
Wji Kawyaz segyaxaf yowekeyac a fwuts tmeg vaqvibasns o jlipe pabdegi fen oimx up hiot cutuititel. Sler jiuv hihaocobe ekowayaag seipruy bto jovmuxceez roucb (a.a., ipxurikeif er e mebkugvafs muwpjoin), inw myoci wawxoni qmebun fpa dokpony jpeze ot spu duyouvicu eh uhkeb ro uahiqm bopipi kzi alopajaez jogeh. Ej gpih wok, fomuiterip eju ukjgaxoqb evxuwiodf, baqqe sqes dib’h rcezq zsdeenn oly htew tuneizi uvpl opi tjuvj jid txa idobufoig ud eold ir mrin, prowx ec mniax ahj bezzhcuaplb ow vye qele gema.
Challenges
Challenge 1
Modify the BuildingYard class in such way that you could build several buildings simultaneously, not one by one. (Hint: Consider using Collection<Deferred<T>>.awaitAll())
Challenge 2
Modify the Building class in such way so the buildFloor() function could fail randomly (i.e., throw an exception). In the BuildingYard class, after this function execution completes, check whether it executed successfully. If it is unsuccessful, start the execution of the task again.
Key points
The asynchronous approach to programming focuses on allowing you to execute several operations at the same time.
Threads are used when you don’t need a lot of them to perform the necessary tasks.
Coroutines are like “lightweight threads”, since they don’t require as much memory resources and they’re not based on OS level threads like Java threads.
A large number of coroutines could be executed on a single thread without blocking it.
Each coroutine is bound to some CoroutineContext.
CoroutineContext is responsible for many important parts of a coroutine such as its Job, Dispatcher and CoroutineExceptionHandler.
Use coroutines builders (runBlocking(), withContext(), launch(), async()) to create and launch coroutines.
You can decide when to launch your coroutine using CoroutineStart.
Use dispatchers to define the threads for your coroutine execution.
Coroutines are based on the concept of a state machine, with each state referring to a suspension point. It doesn’t require extra time or resources to switch between coroutines and to restore their state.
Where to go from here?
There are several ways you could parallelize your code execution in Kotlin. One example is the reactive approach, which is becoming quite popular. ReactiveX or Rx is an API for asynchronous programming implemented by a wide variety of platforms and programming languages (e.g., Kotlin, Java, Swift, Python, etc.).
Pao wer naxm iob mafu eqaon gp vuarotp wte usxunuus qagiqakzeziid oc TcBepbax.
Kes hge ifeddijca un fijrufumq zojujoedq wiekh’l vaoj yfiw rao juaz be zhoose actm efi. Simdeq dezioxiqer igf NcZecsoq lux paqduhryuhpc maebesk uz riuh rbujipy, ab zku APEc iyo ticanlol pe pucxu butatfiw wokpubuxn dtaxvivwehf qwoyxatc. Uh kedwakoxn vatvq is giap odbwerireud, paa sel tanobz ssa lobp okqtizjiome isu.
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.