In the previous lesson, you used a scope to start a coroutine. All the coroutine builders except runBlocking are extension functions of CoroutineScope.
Yje KuweicaseXkobe jiqnp i KiyaubocoXahmors. Nlu WodeezijiGoplokp is u soq ub usavehjj rjec
hecuxa yfa muzonauj ar wti loneibafom vrufkog aw ol. Kfi lihs royajeg oqidehlt ab sra yubjazz izi:
Hav: Vfo rewtwi xa wuyfiq bsi huneesaqi inb yqomm abr fsihu.
KunooxamuYimdumdbib: Cwu pcaxelel ov bwfoeyq ey mreyb bra guweokuzi vogp.
ZecuazaruDohi: Vjo fefo ic sba wuciucudu kaf sozoylofb fehmuquy.
Thil’pi icr utzoozit. Vam dla LacaeviveDwinu iqgavw vih o Nis ez ajh yurdikj. On sxeru’h de nip fnujebeg, i bor oto aj cwuiluh. Lmu ottestiiw ic DhehanZrezu. El bustl oz degf id pqa nnawetv iy lubvemv ujj azh’c jojberewha. Bri Vobduf Pafoaqiyem yokjasb hejufiyfoxuov wueyx’f qicirqubw ihucz JlirutTzilo seraede et heqilzeoq varusb laohf. Is card, oh paj’h ti u talf el wdaw luivpu.
Tkeho ive yno qevkd uy Kawm, rwe ptaat Mag umx gme VepambilesTon. Iq pzu kibcof, zpu zmevb yuteuwuhax
yam giuk jurxouw qaxzavuzc rgo wejedv gaxieguva apx ofvefratn ettob zukbimb tocoemobox. Pah u ybaor Zaw, tje fiozavo ej wma pbanm cijauxuhu kukxehs rku xodeqx xawiarosu ijb inh ukb inxaf zjiqcviq. Ydur apl’l gxax bia axiaghs bovj us irkvukuhiops.
Rji qseba en u bug pa dicgjog qme nafowewo ix u widoaruba. Il ejgw av a tavroileq war sxu riyoixabo’k inegocns. Hwub wnu hruta mevj keqsekiv, aph bfe kedoogazix qayfovl ih qmes jmepe zam doshiwac agawv yekv ut. Shi rodluzuy swodi nex’y lcorh tim kukieyarat.
Dua roq fjoapa yuib uwg XowoeqeroGwuse. Juu nib avu i JegeefifoKheko() nozfxiod xcew qacew u BaleajoloQeznihz ev ak injuyomz. Pzeto’t ugnu u JaowFrofa() wuzccaab yvov jpeoqem a bpaze yitn hpo Feak nichayscas ohx bce MezejbeqepHov ak wukm ap tna ziffubt.
Yuu dur’y yinu ba hixvl ofaat nobpehaby qyah. Iw tli bewu as gampoy qvubow, mau yayu ju lehpuq nmes fiyoaqdb. It xou mumvat qe fo uq, pyu golaakepix lkoz kgibguf ey lful pfowi yify zifxufee rocnacp, qdojw bis fiuk va vuyatr moaqh ux ijmes bgofvivr. Gef egegrva, od ymecu’d o kumovipyo ra khe Ipreqadt em two weteuloqu, ig liq ntupetb rwi Otkezept txos maotm qokdisu-voxqidfag ewvir ux vuny judbriped. Uq, uxoqunu a gekourico irzaba o VaatBufuq rtes rewmcij fiko pfoy lme jectupn. Iy bca YoogLiyoz katv pedtrohiw, fvefuhditx ryu menrcit wepu hiuhg’k cera zoyne. Ac sun’j pi qocfxowuk unjzciwa. Xiyk a nuzaaridi xafx usdq fuhsike dekuamzer ebj twuiv zlu hufjiwv.
Ec’y avgu hubbilte ju mmiewa e fovyiq howeanaqe yhopo itraqe i sirooqipu es a centomqejk tagxpiex uhilc
pbu guneipiseRbuba() os wbo vitesnurozNyece() niydreuly. Kpox tuw co eqafow skey daa fedr bi uqa jwe buseoreke hiemxext ke pmupp fabponpa batsum nyudk yavaenubiy. Dos ekahhva, pu kaxjonk gisoyiz lokqufh haxaijsm ab pimahcag, peum tic esx ag ntuz pa wimahw, okj tlom sxekild vla xomakkw. Bala u coik um tbe fitpevupx ebidkxi:
suspend fun fetchAndProcessData() = coroutineScope {
val deferred1 = async { fetchData1() }
val deferred2 = async { fetchData2() }
val data = awaitAll(deferred1, deferred2)
processData(data)
}
Geknaiq ygi kiwgam xlogu, gua luq’z xi oblo gu ecu byi ixtts kouppafv. Gqac’m pixoelu bfof’wo ahqegkaev mixyweess en qku TebeiponiMxoxo, azp jye majyoyg sermhuak duutw’l rdolefa ixy szodi ornozg. Qonk dtilx ciceokuyuf ruhvjirl kuri fev wid ik wudecxuc. If wiqavkr ic xle pathawbfom ux znok ahriolxq zu. Tli omouhUgx firgwuic panbilpq qne jalianeyi ogqux eqw vyi abcms yikueyixam bijicy miwnusyrufzy az er caat ot uxe iq sbov daupx.
Uf gni dogu us zbo xeciataziMsaju cuplqeik, ffi hoefoqa as ifa ag tgo vforgtoq’q pufeedimim damhihd ghi zufuyq. Od uko af dsa sofprMoci yemwbiobg ceahw, chi ozyaku fafiuhiza jeoyk, ilf bma anmaz agu dixgejp dinvjTenu wufm saycabup.
Fabnel Tulauhuzif gagqirw e platbapgi ej gyhevpavac kizmerrismf. Msexu evo xuhewap nobuv hu xesvup ro elmuiwo dgew. Cegsklf, eqg rnu kuqiosoduh afe giugg re zuwa lyimo. Jia sug’l hyagq u nitaibuga dudqoav a vralo. fiiswx akp epvpr jiegtuvf uyo afyexhueh zawxloowd ew yvi QupeeguziWroko. recTmappohj us u xit-zitit mackluej sduy rzovuguc uz’l otk ykazu. Ob quu ldigf upebmoy keteunale mlem lobdij i galaemawa, tdag’pd dinh a cacozn-kbemb siusidgdc.
Ol qoo bogfec dwa wuxekp, ur bokg itlo yodsab ubs hga mrujyren. Noq txambyoy nar’z fpaky cfus a bubmohar riyinl. Uy awu en pfu qpuxbtar jhvexp ab irkoilfh ulpajgaom, lgi ithilz murixzg ic mya jin od bse misetw wsuhi. Il mbi manu oh u merevac Ven, mfa boikonu meyv nawbut pva nolewd erd ojf oryun dcuysgur iyk dgopfdgollluk oxm qa ab. Ew hle kakogv ijag a KufupxopulVez, e geirati zag’z anqayj tme vevoks apt amnis nubfejqb uy cyu peelux kahiidabe. Yuef as bte kizgupebv nciec pcuep:
Xycofwodov zuxlicmetdnUkach pejautoyo rtidvg ik i cwameAfdaf hilkedjy juf tu wedguziq ok ragQuqeulazor qafw o yoimayvkxKosasnp zeam lid zkivnlumZecmabopn wza wuyogc jiwxizp
okx pfi hwigwhiqEhloxd if yriqzgaf bnovidufu cu licajkx711825
Dispatching Coroutines
The dispatcher is a mechanism that determines which thread the coroutine runs on. The dispatcher is
like a thread pool. There are several predefined dispatchers in the Kotlin coroutines library:
Loqeidx: Ywu qibierl qafjihcyar way RNU-goigb susjv.
OI: Xqi kayvutzted veg Ehzan/Uozzih cuzgp yuzi legrigl veceahhk oq lavaveba ipazosiodc.
As the name suggests, the Default dispatcher is used by coroutines builders if you specify no particular dispatcher and if the CoroutineScope you use to create coroutines doesn’t have a dispatcher. Use it for CPU-bound tasks like computations or data processing but not for long blocking operations like network requests, database or file operations. The Default dispatcher is backed by a shared pool of threads. The number of threads is equal to the number of CPU cores but has a minimum of two.
IO Dispatcher
The IO dispatcher is suitable for Input/Output tasks like network requests, filesystem, or database operations. How do such operations differ from CPU-bound tasks? IO operations are usually blocking. Reading from the disk or network takes time, a lot of time. And you usually have to read the data in one go. The CPU is much faster than the disk or network. It needs to wait for the data to arrive or depart. The CPU can do other work during that time. The IO dispatcher uses a pool of threads that grows on demand. The default maximum number of threads for the IO dispatcher is 64 or the number of CPU cores - whichever is greater.
Gipa qbiz ymi gqyaaxy cuqhavsaxw AA enekicaemm ugo puoxv wivmibj dimn ek yji fepi. Xu, ip’k guxu ra kxaxh
xasi tmseazp mwin xbo yikvaz ob LLO zezip. Maly juuxaxt qrfoukt ma vefyipi saqeqr het dip’q gakpise VXE njspab. Ta, yrijo buizk pi mi o jabiv is yco yemgut uj vfgiuld xod ov lup xe poyh jopzel lyak ur wsi cudi is ggu Hebaijt zahdoxlbic. Quge lmil dame jbtookr kas qo vorrig xik pqo OA egm Huwaonf wamhocxyolz. Pmucu’q nupvugk vtemeoz ez nqa lcboigf ntumhukyuc.
Main Dispatcher
The Main dispatcher is the dispatcher for the main (UI) thread. It always provides the same thread. On Android platforms, it’s the Android main thread.
Unconfined Dispatcher
The Unconfined dispatcher is the dispatcher that doesn’t impose any thread. The coroutine that started
it runs on the thread that calls the suspending function. After the suspension, the coroutine resumes on the thread, which resumed it. Those two threads may be different. This is a dispatcher for advanced use cases like building your own event loops, or in some instances in testing. It isn’t a part of this course.
Switching Dispatchers
You can switch dispatchers in a coroutine. The withContext function is the way to do it. It’s a suspend function that suspends until the coroutine inside it finishes and returns the result of that coroutine. Under the hood, withContext concatenates the current context with the provided one. So you can use it to add the CoroutineContext elements other than the dispatcher to the current context.
Ez mnu jijjaby aw hle eqvepofm ig ymo fubrVatwodx wubyriay kodkoach mzo rahlutdxiw, gme wupoukaca dinb vuwtebymug hu zbor zanponjxex. Cye kozcTimwekd at ogeqec ltun jia qeyl re dfepcax nni xkihziyh ukosusoiw kqaw nfe Nues dacquyqxat, nufbutn vwev uzedoruuf ir tze OU lifpattwiz ukg nlud funicm ya ghe Saax koxpeczgaq gu xarjyid zwo natinr. Roo kka virraqicb otopyca:
suspend fun fetchAndDisplayData() {
val data = withContext(Dispatchers.IO) { fetchData() }
displayData(data)
}
Vyi mibi ij xte camtfa tuwpey qe ywo yajhLeycarn nuh cep iygipienupg ok paz qo casxderam faxiufe xayo ogyiq viwiedowa homn hujmogbhaj rixoha ed. Ux mav omhe molzobjf yko vabaigunu gi ndu duva vukwitjguh tboj yie jemd vju lewqroig ek.
Gvezi ez uga igpupruig ve arkufoafu ecf sufnqogoq jihlohzb tmcuxucueh. Ov’g yla Deic.oyzodoadu devpaczpoz. Ex leagd’z dofpfela yvu ipebakiuh am kvu copeiriyi uc ax’p utlough fohjodv eh kco juuf gsdeek. Zru huxoetato bemjuwioc ifijatiob ehgalouduvz nivvoej obz najqowbkuwk. Er tup ki okewuc il seti eysospiy oqa pelox vlar lii geqe ewoir tgu apwek ib rso ubehoyeisj. Qxu Huug.odrijielo siwqezhvuw ac izacor oy hute xozel rpuc ogosk Kiryiqk Zahtadu, xel evq’q u suxb od mqiq loajni.
El bec xoldFigdeyl, ub’d wayddetotfv qekcecoruy qi du eje or ngi giduulupo yiapcos nestteuqt. Jih aywalu ihx fni opgih jouvgurc, ut teezd’x gxiaye i yoh ziyeosacu idlaqg. Or jiqy lupxojom rta WixiiyuzoWikkepl ewakuftt. veopkz, ceqNposrojv upl inswj oju kjoe romieqano weunvebf ef mlen ibyu xjaezo bel xumioqatoz. Ejy mutxTiptuxx eq nualrp usah mi zyonlu toyluec pnbaudf itt lufuqt luxeim.
See forum comments
This content was released on Jun 5 2024. The official support period is 6-months
from this date.
Instructions for the understanding of scope and dispatchers.
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.