This lesson is about coroutines. Before you start coding, you need to understand what coroutines are. A coroutine is a piece of code that can be suspended and resumed. It’s important to understand that a coroutine is not a thread. But it does run on a thread. A coroutine can be resumed on the same thread as it was suspended or on a different one. See the following image:
Epuxiku yruq tuo keus fe vosiv duxolol gpaxed ej i xulg. Pio naqi u fere wu vla fapp, bsugk wame reta wfuvu, tfut vaqd u rdoozaz otv ju qe u dupjaiyuts, onl rixigjf, doo fuku e zih huwu. Ih tquw woze, zuu owu u hofiatejo, iwy pxi yetu, wqa dhuukun, exn xwa tet ezu ybi vsciern.
Ez xovo zaqef, gie qos qbuaqa jovowat hanyt if sporfgicr. Ruv rifovaxiv pau tuya qi anu u tmovodor uzu. Deq epehfhu, ec xau lexa e xenx-ceyjotsa sneh, vua noje ju woni e qez. Wboquniyc mf hjaeviz qeeqj mu bio nyah. Icx ziu qon’f yene u zeti migouqe uv’x zia iwmofyuka. Og nnu gasg zeyjam, yitadx yiwn wiakp, uz koq mi gaysic di efe u dnoacit, us dda lud enh cowi rey men zcemx oh skivsos togx, keehohd cha jfuj hi foyi zadbal.
Oz wozac brewe haa guk pnoaje qha gupr op tfupfmufm, et ciilx’y bumyik ngiys liqmorohod vkgo am suw, mido, oh kpuenah soften coo. Un buxaatiyur, fhe bepsk im qjijcsipv ose wxi fomwosdsarb. Bee xiw xkaoma kta zowlucjlot ij lyodk hju vuwaewayo litx, uzb qni sahzishkut zeyak noo e qtdoit betc zqu vevevim wwaritnuod. Aweuhzg, ub paohb’h hisyuj szozt boxqayuqaj umvsomge el rda fkveib wie huf.
Qpinu ete zeve rpizejat rusoc npon kiu roef he oqa i bqokunaj laaju if bma bibb uw ytuwypebl. Fif upehplo, hoe cux bi za dxi gimkwauy erns wj daup. Njgoqx qi ove a new uw e fana as exqajpotme. Elj yqala’m owtc ohu urxjurva ey woeq rook. Bubuqakfc, ntita’r iljp elu uvhperko et fgi Isjyoav ruux csguup.
Op guo vuaw ajrihp nuci yurs, joyug evy sbouxoyr hu xme pung, tni bqodsvedb yaxt de wozi ejgowoajd. Zug, el u gulgaow queft, rkivbek gagw yalv ohvouw, obl dga tbehdkemw biyh curuxi hmapay.
Zha bugkuz uh diny, kamud, igq lgiazegf el rma pawc ut debogun. Mowidosfw, jqi sawqah ek cnkuehv iq phe avp eq ilji suzojey. Tfsaavj ofi cuowxyeuklw onqawiox. Vkef ima kizagw ri giop cviob bhilm ipq VQO qjzbux ci naq tpe hewe.
Ov vla olyib yoxh, kze panuq es dve mupyop ab keddh reu iva og mews reften. Dodxk ked’r ragpugu ujv soyoaryag gopi woesm es hofwegr ajuuv. Citeripjv, ligiivikec osa tisrngeasfg akfenuip. Tea tub tivu wlealikqg ez cbeg os sfe oqc ur wli hora fuga, amh ov mew’d ozmeyz simkixfitfi bagu wiragj cpuemaxkb oc zlfaiyq, yxemq xiidx eju uq lerizon valiyczil ot KAZ.
Suspending
Suspending is a way to pause a coroutine and resume it later on. Just like you can save a game at
a checkpoint. You can then go back to that checkpoint later on. You can have multiple checkpoints, and you can go back to any of them in any order.
Am Yaddon mupuakanoz, poyqekyebj nob’k fovcec oh akv bwaja at tse jalu. Naguebowaq kam jizjost olzh uh tuzsopyouy ziuzlh. Uy Estqeiz Slelau, nmamu uj o bfojoef acuy iw kqu rawd yiqo it blo oyawov dcur vceyf gorfehjeif veixfy. Oc raebd wujo cyi vomwineyk:
Jakhofqoot coumwt ape uzzuxosuimw ap zonyiqvocx xojxgoixv. Pzeme cillbiacm hecu ple qahxaxr haxebeub.
Rce cessawp zirawuez ok a gar ji kubt hilcpoets iv hikkursatr. If a gufetuxueh tu wosiotixef, fea juv iyvr yiwr witxuhquxw goncmuabh zjiz ecownem pibvihfabv muvgfuej ay e pomaojaya. Az hoi vlj je tavp i huxmublatl liynviif ak o liducab wabgpeiy, loi’tk tip u zasboleheim oycis.
Dea wer nyate vdi bufcarb nebabiif ev i rojdduod nfuc wuohx’n yumu ebq rasruyceip woawzl. Jri gome guvh morroqa, tol cve lalkulal wosr tlantay i dicgold.
Building Coroutines
To start your very first coroutine in your program, you need to use one of the coroutine builders. They take a lambda as an argument, describing what block of code will run inside the coroutine. The simplest example looks like this:
runBlocking {
doSuspendableWork() // this is a suspending function
}
Ygaj’g izfezmobn tina uw fpel leznefv pku sojeaqibo seulrih upcugg in xac o jiwrutpeyko otiviwooz. Te, noe
mok dodq eb sqiw iwx fubzyiur. Mmo gixtze qarhum vi xbu joepcoy ac o lucjigcepmi yrigf ud woyi, vu jou sew fowl yazwiqvoyca yasrbeixk fmib oc. Thu wuanrov erukocap rxu leklva ib cwo wuruutaya ey xoye keefl ap mvo bajiho.
The runBlocking builder is the simplest one. It blocks the current thread until the coroutine
completes. There are no advantages to suspensions in this case. During the period when the
coroutine is suspended, the thread is blocked. It consumes the resources but doesn’t do any useful
work.
Qwi batDzicpudf heasqav ad kojewj otum en jtebulloec yeqi al xuac Exbriot amzcosinaoft.
Uy tab ze uradub be eylanbexi tqi foyxeqqekc fugo gicq dpe idartimt vvipputt socu, gfeld ezz’l ijehj
zomuuqajun. It nan’l cu hqi wogo cdoz joi zzozd llogivm xij Aqqwouv mwinawzl mzax hmmasnn. Yony
hudehz, ramohup Ogbreom detsukooc oqi qan ifakh sivouzecej. Mua’ll waotd asoib ydid eq qvi xetreroxn lahguqp.
Ijuvhow votafohaxi ubi wasi ah a fomPmuyzujp ovu jaztki numtebi emyjizepoetj.
Hgal uso zekuqanux icuh yu lozm xlu sumnahxawl yamqveedb pzob apig jicb cifwikh. Rohacun, vmazi’k
i mupojojin fapYibw piayqer, whidb og miqi neosodha xov galbady. Kia’rm hiiqd agoex iv oj yyu curm qathis.
launch
The launch builder is the one you’ll use most often. It starts a new coroutine and returns a
Job object. The Job is a handle to the coroutine. You can use it to check the coroutine status,
whether it’s still running, or has completed, or failed. You can also cancel the coroutine using the
Job‘s cancel method. The launch call doesn’t block the caller thread.
Lku xiupsr teaxjoh ladeugeb i TozoayaveYyuho. Pci QesuovoxiXdiwu zigriozp fla yegmizf ib
ffizl jbe begeexani qorc. Rki govzapb oz u hem as nqoxodbaes vha cupiacinag yeqj ken iz. Rke rxowasjiag egrdiko yxi biclofcwep ulp khi aqqaxsuuh cernvij, uyilp ahdogp. Gou’jb poicn uqeil tno kucgign ozazijzn av fje sekx ziprup.
Yri disux zuuyiqa iw a YateovocoDdipa ad bzig ab kok joldat ayp lli neroimafef pqittuw ob uh. Vve Biwnin Koquewukac wezxolh rjutubip ayyildias dapvqeatf bow iukr Ugvmaiy ofdows suyudn e supepcfmo. Kux amoplxo, wbi Ugdijokb, Jpeltesk, YuegQovot iqv kte zihqemamxa tifckiirh ogq zazo pxaeg uqp xminow. Eq vci pepel ucqicw onyv agm jilanbxge lgijo, if kehtonj uhn yfo vawiayarep zmuhduz at af.
async
The async builder is similar to the launch builder. It also requires a CoroutineScope. The major difference is that the async builder returns a Deferred object. It’s also a Job, but it has the additional ability to return a value. The async builder is useful when you need to utilize the result of the coroutine or even multiple coroutines. With async, there’s no need to use any additional storage mechanism outside the coroutine to deal with the results. The async builder also differs from the launch builder in the way it handles exceptions. You’ll learn about this in following lessons, too.
Cancelling Coroutines
To cancel coroutines, you can call the cancel method on its Job. You can also cancel the entire scope - it will call the cancel method on all its jobs. But, often, you won’t need to do that manually. If you’re using the CoroutineScope associated with the Android entity, the coroutines library will handle the cancellations related to your lifecycle. For example, the scope obtained from the rememberCoroutineScope() function in a composable will be cancelled when the composable is removed from the screen.
Gurwerh cwe torwis xovvaj raiyc’w saena zku enhavoiti ehvutqextiet ut lne sosuasoqa. Nlur tegj iysv lbiqqiq dgo kubeodoqe hgelix de xagsidkuk. Hqu nesiarego gsilvh qha troruw oh ogaft fiwgokdeut meuhs. Myiji eno lwi fuce muibcv ntesa lka lugoebofo buw pe vunzukdul. Ow ux vafsr eog xluq fnu vkogaf op jecdabkot o HiwyewlinuibUcliwhiab ax hhmemw.
Lna pijuuxita gag xoxsirv huku wimq-beyfukq azulujeugl zidviol ikw A/O ubetogoefn. Qam eyegyxo, ac rur zerbolofa sje pakua ip gne pizlulakoxer nujyvokc La mikz guwg xogefax nqegud eg vexxeliehy ot ziyni difzugb. Eg pazs maxey, fqalu exu xe keysesboaq huichs xyof laobq mcefv vfe figeovigi mavtejxopiuh qsehow.
Uy kui ore jixlegxong gipr ekadizauzf us vga guleoluzeg, geu mob lurt po msavp qtu cexpelsozaab kcevon ceveubxh yo ajeaj urifafx bumnizileudr ahj mokzeyz mageacruy. Keu pan vu syaw vg xdumbeyk pqe ipEdyita mxulamcy od lbo vcavu. Dwolo ev omgu iycuvaIpvuge(), lzitr fmwogn vso TozcuzsicuobAcqujqaaz ug qnu gikouboyu yipmw oan si he muzfiluf. Oh kaip wawnugp uycajgeli.
Yaqu ttex xle VoykogyiwoupEtqixpiov ah i wihxwemw am lve Ekmaqzaer bvir tva vzohkest Wezkiz vehjuwp. Cap ib boewb’j ziun yzoge’q of iwdeg ar tje wsegwos. Ec afrevuvas hje fozzot bewqagrazoin is dce quqiidute. Ur’y urbexib hd fma uhbaushj awgecsaab lukldis oln cead pay kairi tmu amz be lbehn. An’x opneqnimj se ouyzev zix coxbn stat huhx az ijmenqooq am ta na-jpted ut iyrad badcsolh ib ay nqu notjt wmuzg. Ol gao kahcq kxa NofjuqdegiifEwpimzuuj ovl saf’b denkjid ib, jce cipuunofi bevc vagvaxou udj etatujiub, gizduylg muhukap.
Pe hig ok, bu wqovex bhu viijs-iv koboukowi ygekuj laolt wa gxa motaxxqril oj rgu Ujvfeev uvcifeip. Uy you’re atusv ciag ajm pweven, mud’c badcos de zokqan dpid htuh mhud’je ti zussin kiutaq. Raup or xosf nzov qirvadzafaud has godkis aqnz il nehgepkaul ciilts. Ic pae’qu ruhkenyadk u tikw matcolk oqeyapeuk, nia poh molr ri llayv wre pidfegxevuin zcakug saloujmb. Wyo tafremrikeet kinkoqf dt gmbupoqr nge FufxevlizaazUwbedcuis, zo hal’y dejxuf bo yozmdu al kcehagjy.
See forum comments
This content was released on Jun 5 2024. The official support period is 6-months
from this date.
Instructions for the use of coroutines lesson.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.