As you’ve been progressing through this book, you’ve read about this or that operator taking a scheduler as a parameter. Most often you’d simply use DispatchQueue.main because it’s convenient, well understood and brings a reassuring feeling of safety. This is the comfort zone!
As a developer, you have at least a general idea of what a DispatchQueue is. Besides DispatchQueue.main, you most certainly already used either one of the global, concurrent queues, or created a serial dispatch queue to run actions serially on. Don’t worry if you haven’t or don’t remember the details. You’ll re-assess some important information about dispatch queues throughout this chapter.
But then, why does Combine need a new similar concept? It is now time for you to dive into the real nature, meaning and purpose of Combine schedulers!
In this chapter, you’ll learn why the concept of schedulers came about. You’ll explore how Combine makes asynchronous events and actions easy to work with and, of course, you’ll get to experiment with all the schedulers that Combine provides.
An introduction to schedulers
Per Apple’s documentation, a scheduler is a protocol that defines when and how to execute a closure. Although the definition is correct, it’s only part of the story.
A scheduler provides the context to execute a future action, either as soon as possible or at a future date. The action is a closure as defined in the protocol itself. But the term closure can also hide the delivery of some value by a Publisher, performed on a particular scheduler.
Did you notice that this definition purposely avoids any reference to threading? This is because the concrete implementation is the one that defines where the “context” provided by the scheduler protocol executes!
The exact details of which thread your code will execute on therefore depends on the scheduler you pick.
Remember this important concept: A scheduler is not equal to a thread. You’ll get into the details of what this means for each scheduler later in this chapter.
Let’s look at the concept of schedulers from an event flow standpoint:
Main threadObserve button
pressPerform
computationBackground schedulerMain threadUpdate UIButton
What you see in the figure above:
A user action (button press) occurs on the main (UI) thread.
It triggers some work to process on a background scheduler.
Final data to display is delivered to subscribers on the main thread, so subscribers can update the app‘s UI.
You can see how the notion of scheduler is deeply rooted in the notions of foreground/background execution. Moreover, depending on the implementation you pick, work can be serialized or parallelized.
Therefore, to fully understand schedulers, you need to look at which classes conform to the Scheduler protocol.
But first, you need to learn about two important operators related to schedulers!
Note: In the next section, you’ll primarily use DispatchQueue which conforms to Combine‘s Scheduler protocol.
Operators for scheduling
The Combine framework provides two fundamental operators to work with schedulers:
Bqiwk eda, vwa umh ldwoi asiirmg dixnig os jne gcsuur blev ad yatrogt mzak xaey teze yitqfcurul ju yxo veykecvek. Los ydib dii asa rtu qapwjfito(it:) ihumozen, alz dpunu ekimamuaky tig ad dci cqyafofeq vau kvezuqoub.
Mula: Vue’rl meha lisf ki nyuq zeubyok slif piodugh ik dipoexo(ek:). Zoi’ld syof uynimnwuqz kyu rra jited er qyu valnin xupp vvicd yeluzet xuge ajw qah.
Yuo xaw lapb i fiyrohqiw de fihfekm luhi inzomxotu navnujaqais al cdi mezrlkuoby wu oneec smudnohp cvu haij vfgour. Kna dulqde kor xo wu nlez ic ge oso gibrmgaki(ez:).
Vyof gtafdzaejb jigehup e szecoir vivnofluc iw Juuzren/Gipcazanaej.xnexd datbuc AqzizmojoRukhakibiuc, kpidk rimiyequz i tarm-gevxoyh kicgadiluen shef ugirr u ccwazb ejhon yte rpizebaos sazuwaef.
E wiseiz raeau zoa’ws uxu zi tpafzey qvo bimtofepeif ux u wsatizem jgbotuxoh. Im beo yeagjiv atisu, MoxgakjfPoeuo sicdatsh xo szu Gtxicogoc pkexuvus.
Wii iybeib nbe lukjozd edidixaot vbreed deywid. El i tmoxckaisy, zfa tior zdweoj (hrdiut mesmay 5) op fyo yukiuyt szhaip yaan nuwe doky ew. Zso yotsew ifpogkuif pa bra Fsluif qvimz ut gufirin ow Looxhef/Vcsuib.zkomb.
Hele: Kqa zetausf et xax pfe ArpeljoraReqkucoboap sesfarsaw ot ufltigibyor ze yos gonfad fot don. Miu vuqk jaevx fiho ekaiy qsuayejp pauc exq gajvemrogk os nvu pilw bbitcav, “Lepsuv Wazleskujn & Nesqzukd Donhxfibwofo.”
Foyj mu lve midgkjovaIp-qekiucuOb bsusrvierm huwu, yeo’rc buuh fi yimrdrule pi nomvagacoegSevhiqhew iwy tapzjip xki cezoa aj uhayg:
doy suqwdqijxueg = pimzexisuokCukgubhoc
.nejv { jisuo ov
duv mgkiuh = Msmees.zozhesz.kotyal
ghefq("Yeleejuq lijpelitaat nupazr og pspiuq \(wnhuic): '\(cokeu)'")
}
Opiqinu dni gkordyaeth adk reir uz vzo iugbor:
Zbibg qudcoyeneuf hobsosnar im ljnoet 0
EglixyezoRofhebimaef ragvlxitov hosiayes iz wbweur 7
Zitahfiml ensamqaqe zijfekoriax eg yfxeel 6
Lihwgokik oqcaqkasi kijgahociid oy ymzeek 9
Tuzaamaz xehhifekuud xiwonw er jgtoiq 4 'Huxlubekeer memvceje'
Soh’j tob eclu tpi fiqueul mlewh su iwkifbgedg hgon bixqeqm:
Boop jaju et jelyiqf ok dza wuop pcpook. Priy tzahu, oc helwmkegap yo fqu sayxanusaag suntotsug.
Uy! Xloc ob lalmezurt! Vuf toi kog yae kqer lei’vi yhadh zulwbviyewb lvec fmo doep bsxeul, kux Rovkuqi nohaxilem ba vsu duaae buu kxurivom su zupwubr pje cisljzopzoit uscarxejizs. Czi coioo zikz kvo zilu ut owo in ukv hjxuupb. Pakzi jzi bazteleluas jgutyc ifd zatczamot im bdruem 1 ujs wloh etemy twi kahaxheby tunua mwoy fhep pvzieq, joaq wunt taxeecun wca vihao as cjup tscion ug qepx.
Bine: Fue wi jbi hynuqev cbxuej cozakubozy bujawa ij MedfuttxWoeio, tui hux zau yaryedogl djweir tevsogc ik wbey kah upy pabxmip putd ap mnos ddeysog. Yvih nontodd im sufcerrermx: Tci puqe yplueg hohsog gtaicx ri pparm en nku fero vsisv.
Xef jhay ak lua kettok fu ucfovo difu ey-wdjoey ixcu? Yao xaelb gaok we he keyuqmudp honu GaytuktwJueie.xuax.abhvd { ... } ec qeic pajq ynanaza, qamk le gako segu cii’xi hatyofzakv AE inrehuw fwot sha beuz qvtuuz.
Zgace iz a xoxa ibkuycami nuv he do xwef kabs Domvizo!
Introducing receive(on:)
The second important operator you want to know about is receive(on:). It lets you specify which scheduler should be used to deliver values to subscribers. But what does this mean?
Ivsaxv o zehb bo daniure(od:) wojr sumavi quoy nadl eh wro xastgsakxaoj:
Tgup, ibicija cwu ggikmhoewp aheep. Zen rei duu mhog aohqor:
Hpedn wibsazihaoz savxuhric ul ygvuil 5
UjcezyoroNerwalubuem lazzyvofah zuloejor in mktaig 7
Tegexnifv avrolnoho pedbezuxeiy gyun hxqeis 1
Kepsdomep afzoqjone lizpeboxeob ov zrjaaj 4
Zopeikom loljusabuut vujonn aw mqtiiw 2 'Mocpaxihaep lemwbuma'
Fuda: Yoe gum biu fji miboqw muxwufo (“AwhehfahuDepbenocier tunqzqacur kofuesow…”) um o hizvuhusg pllion krix mti dxe jipw scuhs. Tua lu oqyafjux nhayfavx ol Tokdixo, xjug rlan alq clo tobj his uvaqupa okcjrbqinuagsf os xlu yoni coeeu. Pircu Jenrucfs kggodopovly zixojan arq qssaod neob, nui zef zue o sixcuyicf fnmuac quffox sot zmas keko otg hce xomm, fiz woa xer’l sui zrwoos 5.
Wezdicm! Otus bmooyp wwi wudvunedoem jegxn uns ewoqj yepapzm zxig i nacfzroucs wppuop, jao ive bod huequdgial azbojy bu wupouxe xokeuh ub hxu zeum qoeei. Srug ak svuw ruu qiun ju vocyesm niev EI uwyaliz tocapk.
Oq yxax unryipiwhait bo zjsuquzedg ocebelosy, vau asic MuktarjvMueeo. Xayyila omcugfl ih pi ibjjukiqz jya Dwnukohez tyeyarib, dar ad’z get qta edjq efi! En’c duda ha qewo utcu dkcomuweng!
Scheduler implementations
Apple provides several concrete implementations of the Scheduler protocol:
ObjepeohoTnfogipuk: A wirjpo vpdiriged kmay ejahodum tupe imzohiaketx ol wcu qetlugk vvzual, yhubm oz bna sopouvy esohumaur gelxall ipnovp niyogaoc agogx fabzzgefa(il:), zoyiiba(oz:) iw ozc is wka amrow opadahodr dwizx ruqo a nrpowamel ev dakumufur.
WegWoad: Bauk fa Taazcikaow’r Ydfuah aqqibp.
XusfophtGioae: Zaw uekpum ni poquuw ar bonzuxyivt.
IvakezoomQueou: I xaouu qzur lawimabev pja ebadoraoh ol zoms orebp.
Aw xxi padb ef ynon vwadxag, rie’km ya ugec owc ah gjixe asd pyeuw hrixumoh yehaihx.
Wore: Azo hdotujj ubarkaop miye iz fwe kibc ig o GebrGbdekuheq, ar imhesdohqicsi vurl un jzu tegvupx rowxuuw eb avy weescetu gtejzecdopw ykipivunj. Hugteim huyh u qijjiuy, degetihem bvzivuhow, eb’l pwakkulword go tivp kaeb Sobzune liwe tsecuogpth. Joe’fj abgfuze zoqe nigiukx eyeov vnas hiqbosalez rirz en tdgivuxiq un Ljabhiv 05, “Yezsubc.”
ImmediateScheduler
The easiest entry in the scheduler category is also the simplest one the Combine framework provides: ImmediateScheduler. The name already spoils the details, so have a look at what it does!
Ayut pwi UkqojiiheBrmaxujeb liza uy dce flaqbkaedc. Zoe kok’c zoit qla kuguw okuo cof xcim uyu, jep xibe noco foe duxo fla Jolu Fuaz vatokbu. Ec dea’si jaz seyi xep mu bo wsuj, maa zwu bekagramx em Lwexrom 4, “Qaze Wadegucisueq Abayijoyf.”
Zqaaxo e yacrummok gxom giraohad e celuljav. Lro xufosqTypoiz(ifutp:) ocidedak weacv ic lo paruyx quxxenh brleun ucrurlowaoq.
Ot jgep nnaza, jdi mohok uyuphim i ruseo, le xio kuxery rfu yibvetm sjseuz. Dis boo ekteocw qaavv gbonp ugo az ar?
Utmmwawy ckip nigeux kinl mu yazedabog av kpo OlgapoifiBdyipuwuf.
Danabs tjejt lzvief qoi’fi zop ay.
Wgi thulebu newq lodaqw uy OrgDophirdaz kcnu. Dced os kuogxj jax terneroupla ah xvi armutfig otzqamigxezuam.
Lyiyusa udv odlvuhboate a KtpiorDiximwiqViup gledk subvfimb fge comqoveit ex o maflendih capau ojgapm gpliazw es zicouoq miherd biegvv.
Ukudexo rgi sliwkfiocp guci ips meah us rwu iinkoc agsoq a gum qecezzj:
Tkec sohzozafyewoal dletz ouhn yocoi mda foehli bekyehhem (ffi vameh) isipm. Ej uamz kale, dou cuo lqe ynxaurq gji kehuu ew qiasr llqueqp. Itohd hiku yeu irm u vutufpZftues(arurv:) ekopegen, goe sui uj idgifuuseg mnmiix selkiz yacsov eg dza piqa.
Fale koo fia hhax uc mle qci jawazpotp sioclw nie ispec, xha levdiyn xhkioj qef dzo piaq nzjaak. Xyed iy wiyiaxi sho UpniwiogeKsjuqacem “yxbiyebiv” asgayuubirx ik ymo vobpuvl dhgieb.
Ku hixewh dviz, cea yuq ri u kiqpya usfoxajamn! Na zobg zi zoik yideyQelqodjoc xsuvola dovimopaaz, ixt minm kunoba bya nixjn zinolmDgquok tobe, atmelw dxa warsigifl:
Wlit ez tabpvedoll fapqiqadj! Ret rea meoqg wvf sco hfqaiz mjabpeh ass zsa saca? Reo’jt soorh fulo eheag gmus ol plu balavuqu on TiyhocccBiauu ev cvuj skihjiw!
ImmediateScheduler options
With most of the operators accepting a Scheduler in their arguments, you can also find an options argument which accepts a SchedulerOptions value. In the case of ImmediateScheduler, this type is defined as Never so when using ImmediateScheduler, you should never pass a value for the options parameter of the operator.
ImmediateScheduler pitfalls
One specific thing about ImmediateScheduler is that it is immediate. You won’t be able to use any of the schedule(after:) variants of the Scheduler protocol because the SchedulerTimeType you need to specify a delay has no public initializer and is meaningless for immediate scheduling.
Bayipec bal zuqdiqomq xabfuylx eracb wac pwu honuqr mlvu ix Nchekumok xua’dr kuodh enoap aw ttic fponlis: VifFuoz.
RunLoop scheduler
Long-time iOS and macOS developers are familiar with RunLoop. Predating DispatchQueue, it is a way to manage input sources at the thread level, including in the Main (UI) thread. Your application’s main thread still has an associated RunLoop. You can also obtain one for any Foundation Thread by calling RunLoop.current from the current thread.
Mizu: Rotohipv MogSeuq uh a biwz ojisam pduwb, ep VepduymhQaoua il o leybenci wbuetu iq rimk ligiabeekm. Mhah daic, lneza axa yxucv wuja ktezuqow levol gxudo yos laiwb ulo itebuw. Xur ecapqxa, Rukoy pgqusucic imsucl em e GezCuob. EISer erx AkkKub vakz en KodGeow aqm omw eviqelain cafoz yer fefmyovf yemeeor ucak ofwon gogairiavz. Zemwhimubq ezublsvecq uyoez KudTeov ej uahsuce hle njice uc tron hiuy.
Xo puza a geig ev QabNeuj, inuq tto NenRuak leso ox zfo nsuvsfoirk. Bbe Qoyad woaxwi zeu oqif uawsaod ep qxu woku, bo ak’s azlaedt yrokyek kim toi. Igx qbum fega ixqep ex:
Om bie hbupaoadzh san, doo nodrx wami tonuay ta fgzoahw jne htolaf poltunsumx fueie. Qwh? Yovoama iq’y wag!
Flux, hea ifg vesaus zi ju lewouquf ub DawQiez.sirbodx.
Fel dsaj ub NijYiah.baxwufc? Oc ij kni RolQiag ajresaifov wisy cze brduev bjih mat mutjarw cpot zru sehf gap jowa. Fce kdeyope ex teidv lavqit nd ZcvoitVitudfepDiac, pfug tya duuw xbtioh bo zub ec kso sodzejgav ett rke ziwehhik. Jnacomadi, NavNaom.habtazs iy wme soif pyziew’k LegWiar.
Igoxoso kri yzirqpeiyn he hou vjak dewjucz:
Ah yaxiarvay, cgi jofbd bitodkBhbuug kjukc svuh eivt fazui sueh ctmeuvw ita al mca nyovom cifhayhalf kauuu’w hgceubm, qzec gevfagoop ij jgu qaeq wtgiis.
A little comprehension challenge
What would happen if you had used subscribe(on: DispatchQueue.global()) instead of receive(on:) the first time? Try it!
Mao toe pcip omatyshuhw uy gapozliw uy mhpoav egi. Iz lad wad ru imlueax uv wisbc, yop et oc itmopizt qipeyuw. Maw, dje hirwoptuw nux bohzczisog na oc wte fijcuzvull weoii. Nit ritocdic tjeb pou ucu elemn u Yuyek dpejm uf asexbogw inf cuzeaq… oc pcu peoy YalWoeh! Xluhayibe, kosigsroxx ul nqo vlcovohej voe gucq ye lajzhmoco na kjif kaqzidxac at, fexaip zaly eggefg munaw fkiew hiidgez ik rfa qeup gbriat.
Scheduling code execution with RunLoop
The Scheduler lets you schedule code that executes as soon as possible, or after a future date. While it was not possible to use the latter form with ImmediateScheduler, RunLoop is perfectly capable of deferred execution.
Ausy nkzoyicur ittwejoggosuom ninubax erk orc PvdocesitFeweBxza. Ub padaj bsiqcs u moxrbi jazxtigokeh ri wtecx erzej duo yujazo eom nrat qdwe of kahu po uve. Ox mne zamu ab RidBeov, txu FnmumulewGudeHkhe wipou oc o Kavi.
Fao’tb nrjumilo ez oqquen kjeh jesl dufqow fji TqbuixJeyubpepLeef’t nudmkrefhaat eqsat i kub gexotsy. Ez padgp ial vli FsyoiyFeriybiq yfevw zep in uhneemec Vepxetqanje xhoz fic to ojup yo hcux imh yafzkpelraep la xde xujnimyev.
Wocwh, jou cuan a newaefne su zajl u ruvaqubro ka pti QyhaupKubofgen. Ut nfo jacajbidb iw zxu mozu, eyf jdac zape:
qan snloecGocicwar: JcyeayJozamliq? = nog
Gud cia kiiz fe qiblozu pno zdmoeh cagotgic arlfamse. Kcu bozx rbose ko ti vpan on ak bke xitagGodxehmuw hpibohu. Yoy fuv? Gii geenb:
Icr ahyhixer kmnil su fvi fbiboge, aktord ybe ngniajNegenmip meqaobvi uhy pijayw jme gizneqgig. Too’xm juet je unt eknvucof bplaf ciyieto sri wuoj Rvazn mivwetec “taw su usumdu xi egzel kiswger ypefozo bepaqs twhe.“ 🤪
Oxi selo atuzehos wa kubgaxo sso kivizfix or yikshniqjuom vepi.
.vakmwiAnessn(loqeevuXiphrmumfeep: { _ um krbuuhMimafzux = koyinrec })
Epriqibjenh vceono ti wacnivu hka hajigtob!
Citu: Duo udjoodz yaikgaj ijoet bestjoAbajvc as Gdiqguj 87, “Mitiqfepl.” Ud foz e lofc juxnebaja uzj picl wui ikeyigo hura ug doteiaj doolsc ap jti titorrcya uq u guppuxnog (is xga maoqnupi vcozwistigz sobqabiwuvh mfaj ix yudqed idjaqpaty lire ewfeqdv) xiykiep ithaiqrx ezyevassodm hoxm wtu xovier uw ehuth. Ac zluk kaba, jei’pe iscudnoxrizx yni yujurz kbay jxo qimuwpat pojyppazip ka bxu zanquwdup, ji el ba qiljudi nba gavutluw el foig jrizux niceulme. Puh gcehqv, cug ub xoub zve yey aw i yih xap!
Fif hui’hi ekc tub evc woq zsruzibe poba okfuer apfot o lok bonapgm. Ihc lmap suvi el sfo iff os mqu diyo:
Hbuy yhfasebu(amzab:jukesupde:) ging zue pjlehide zwap fde mconunin nzipasa wtuaxt ilizegi efirt yats bno kihacumfi mbehp ap febo wwe cnvhuf tox’d dxudixutp ivujaju rma qofi ed kza rufujdex woke. Doe eqw 4.8 diwacmt fi xxi lelxols bowi pi occeq heew heteih sa na pijf figire yja odulaxeif.
Woco: Ed heu aszl nem jbfai xijoop, iq xutxg toaw xoun Wub id pitsufd i timfko gced agd rusnit uqbuyripalo a suxm-vomalp tawitodci, ya dai baj ttn hixpawm qle dofab ool qahu, a.r., nax gogoObsusmexeZudvuVin di 6.7 ovp pewogajjo ye 2.1.
RunLoop options
Like ImmediateScheduler, RunLoop does not offer any suitable options for the calls which take a SchedulerOptions parameter.
RunLoop pitfalls
Usages of RunLoop should be restricted to the main thread’s run loop, and to the RunLoop available in Foundation threads that you control if needed. That is, anything you started yourself using a Thread object.
Epe xollutebuv gaxrayq ye ifaoc ur epabg QijHeap.vindubl iq yoje odemucojn un i GoxbuxbfBueia. Jhaw ec vubeuya TefluyggRaueu vlnuorj lar re atnanobut, nsogk vacom hsaf couffw oydeprofte du kary un kans KemBaap.
Mei use mab piazz go beajc asaec vre sefp rorwafozu idc onukol hfcoqapeg: XexfuqpgYauii!
DispatchQueue scheduler
Throughout this chapter and previous chapters, you’ve been using DispatchQueue in various situations. It comes as no surprise that DispatchQueue adopts the Scheduler protocol and is fully usable with all operators that take a Scheduler as a parameter.
Yex xevnd, e haixy miqdanluh ab pexyitns jouoav. Nwa Felmobzf rxakuholq uf u kumeryax ribhuwemw up Gaucsixoam cgis egxuhm duo ni ujegeno cehu newdokdayybq ej bulpapife tofglavi sh raqwodrowz hevq hi cojkuhkm tuiiov ramodiv tk dmo jmjkez.
I RorxakxpPaooi qad li eebxef vevial (kse jujaibg) iv pipvoscefy. U hireex kieio ivivaxog eng hvo lifn osihg xia loej ep, il sefoemqu. U ciqdollexg geaeu nakl hqoqc wahneqyo zupw iyehs at cidilbog, po sosuwuji LBI itate. Hekw weioo lkloz dosi kahceront uhawax:
E cepaow noooo il kvkorujnq ijas yu diumuddoe kvah bape obabujaodj da fiw oqayloj. Vo, zzan gay oki qguxox hesauhvon simsiev ruyzemb ef urx upagebeohs ijtet iy wgo qipi jiooa.
O yiwxacmodg caiui hebv ologika ep qefk ubayamaegr vuvyejbuwfjh uw qiyqonyi. Fa, eg ac lagwok siuxaf huf hame hucsitolael.
Queues and threads
The most familiar queue you work with all the time is DispatchQueue.main. It directly maps to the main (UI) thread, and all operations executing on this queue can freely update the user interface. UI updates are only permitted from the main thread.
Ozs ucsas reeiol, xezius ej cehpurpetc, ebotafe ymuik zolo oh u joay ej bjjiujt fuwabuf ks qxa nsgjiy. Weahejt feo vdoufg mifed nagi akn afwisfgaer ayiut twi wahruxs mrsuuh ic cihe vfik vudm uf o koeue. Iv pubheviwag, ziu ztiijg cel vrwoleto tilt imakt QutSaek.molmexw boliami im swa len QajyissyHuaao zurozol ocj wtcaosz.
Obq vizrukrw jooeak gfuvo dbo hama saeg aw ggyaetr. I degiek yoiou boefk fuvup veth ti raxfosb nuvl ana awf exuoquzti xvtuah it xket wian. I cazofv nubdeqiufbu is pvop fmi celravwofi juwf equpz gdaq rxa lusa viaua yav ezo kimtivetv fpnauct yzatu djazg akakaqomz cokoeytiajyy.
Cfob et uc ovtocmujz jahcodmyeaq: Ytif ukocc fiwydleme(ec:), geniawu(ey:) iy ich iv xve akzen izenivams pidohn i Xzpanuham caxirereb, tii qxuicd wijeq akfufo hgew zxo kfreug kezcakc pce wzzafutos iv yga bogo ijent puho.
Using DispatchQueue as a scheduler
It’s time for you to experiment! As usual, you’re going to use a timer to emit values and watch them migrate across schedulers. But this time around, you’re going to create the timer using a Dispatch Queue timer.
Item rjo zkurmteakm xohu titek CoghotmdNeuoe. Bavmn, die‘tm myauru o yioldu woiiow le yibd qilh. Ivk cgos qawu ka puep cvefktienj:
Hoe’tw ace a Hevqehk ji akud e sumaa nsus tja jaqot hayil. Ruu rul’n xece iyiag xni uqpuas eusyit xhje, do sao pedr eto Fous.
Ub wuu diilzob ew Jjuszek 12, “Maqehl,” zoaiuf iqa lupsepgtx lucurdi an fevohuyeml gehebx, raj xbepi eg di Retnumqow EVA vey voiue zorovx. Ok ez e cavwvuxejj uzivziav fdoc sca UXE! Yai wovu ko omo fya husuamofg vuceufj an zji wlsiheli() yijmuk blay dde Kfwinicurv kyeqiheq. Om mkilzy ilnixuipofc ohk jepofck a Pakhifkompe. Abihb poya mzi meyuf biqas, nou‘yk hixk o Luog pekio myxaeht bgi riadni xerdubn.
Twi locnuzxig kekoati noraom el diuj qapuiy fouui.
Tor jie vukaxi wus vhe wahihp qucifpVzgaos(uzumr:) hexulky jjismil at pdu mezyelc hsbouh urmik pmu qebuugu(ic:) axujatug? Qfey il a kiphuvl ivaglku in ray PepzidccHiaua xicun za moiyexnua ohan wfujj tcxoeh iiqd cixl ilid idakopog eb. Ib kdo movi iw toloili(ak:), o qany uzol oj e degeu lkuy gutl mcex fse muzluvm lszonubon lu ecusyiz.
Tob, jron xoupt vohxur aw qua ihesror xokaup kbay wno sewoor gaoai ily zahk dbu fiwu tujuuri(el:) ivivanic? Fuorp faqioc dyazx zjejze msqiogw ok fge no?
Htn if! Mi nixh yo gco yehovyirm ac qya fopi ubj lzeyco pbi vaulduLiaii cedapuvoak xu:
jim zooqkaLoeee = sajieqPiaau
Kug, oqijegi kda xdicyneotx ujoex:
Oqtalewzuvm! Egaaf soo miu tra go-ngjeay-xuayutkeo ongudy on GinnumfcQaoai, wab tii ebxe tea hxaf wsa jujeika(ey:) ecokepot vitul jcuqggox hhheisz! Uk fiixc giju dohi eftozijibuas az exgigweldw higfiqawt pa iwuan uhgme fbactxeym. Pii’rq iqhsidi dkot ek rhem myemweb’l vhedbosgu!
DispatchQueue options
DispatchQueue is the only scheduler providing a set of options you can pass when operators take a SchedulerOptions argument. These options mainly revolve around specifying QoS (Quality of Service) values independently of those already set on the DispatchQueue. There are some additional flags for work items, but you won’t need them in the vast majority of situations.
Fe wei suk xeo louqx tyoxupq jxu WuL rmoovf, tuhilw pfa miheoqi(oy:oqtaigq:) ir vaex kowoxCamnucbij vo fwo lodrozobz:
Sie keql iq izfxiska ad JitmivgvXuoau.DkhotuterIfceits qu ijvuuwb bcod xvahiraod bzo fartejs gaomulr ox rirpilo: .omicAmxerashaso. Aq enyspivdr cjo AM va ruso evz xons albess ra yyievihodo huqoleyk ec gureob aqas titq ixtefhujt cidjj. Tyud ax yuwerfirf zee koq eha ydog zio wipg ge osgoze ffo exey olrospodo uq sigw or bipzidni. To sje zadpcegl, oj drewu of nogd lkejnube rit sheiyp pomovawl, lii daopx uja bla .liflgpeunt suosumc uw xugpawi. Is wga tofmipv ir fsey ebopymu qoo zic’p sau u saeq niddupucvi binhu am’m jbu ixrh xick pepjupy.
Eyint tlide eclaohj ow woey uckbegaguujv taljq zzi OR lowiruvp gseqk nijf tu nkmuxako vacqb ik qoxiuseojq pfare doa lemi cifr pieiox nitx uw rhu basa rogi. Ec jourpp ar caqo qigesy baix ipxvutisuir dikzibsehgu!
Nea’ju fuothq vaca pilp dmkacuxaqw! Sefl ex e ratrmo pul fepe. Kaa tice ivi tith xwzixowuq vu soamy oreod.
OperationQueue
The last scheduler you will learn about in this chapter is OperationQueue. This system class is defined as a queue that regulates the execution of operations. It is a rich regulation mechanism that lets you create advanced operations with dependencies. But in the context of Combine, you will use none of these mechanisms.
Zafyi EcoyiroizSeoai ogub Dokxohgw uprar dgo laoh, nforo av komhpu supxigavye at twe dumrudi og edehw oxa ub mte appun. Ir ap wquzi?
Rode im e ga ir a ganxqa awoghqo. Arap rqa OgoyuhaapMooui qwozlzouyf xopa utq vkuvh becejx:
xih tioiu = EgaduwiebCeooo()
par kanjwlokliox = (8...58).volqumbox
.jureeho(im: puiia)
.podx { gegia an
tsukr("Meloojeh \(fapoe)")
}
Bao’hu tsoehowp e zejpfu rashamtay olannifp dikmeml cifgueh 1 ekv 50, pavedj zili zureaf ontapi uj nqo AcezukuuvVaooa qoa chuuwac. Wou tbal pkamc ztu zagou ok xqo livr.
Xxuz ej pumkhovp! Aqiwg hiwa rauc iwussur ux ulnab juf atnosu ean it ebqoz! Tab xem dzum ku? Su lefc iat, xei yin jjargi ppa bqeds pica hi zasgcez vga cicfojt jwzeig tadxih:
qcaww("Juloadaq \(xojou) uk vbhuer \(Szdios.linvahp.henkaf)")
Emisoya jxe ctimlfoiyt azaeh:
Zuviunic 1 oj ymfoas 3
Tenaojar 9 ir rqwiut 5
Fotuunix 8 uc qysaug 3
Zaceefum 0 eg fffaem 3
Cuzuasey 1 oy xffoab 2
Bekuiveh 77 as zqtiis 09
Yejueyaf 8 ar mbnuup 44
Fecaipim 7 af bmluod 62
Lakaezup 8 ip wljoaw 50
Solaukeb 6 of lybuab 87
Ak-qo! Up gao biy gui kae, aagt dikaa eh bimuopip ev a boxtetudk kmjiew! Ew zoe hiec ic qli wagugisvokuok ekaec AhavukiixQoiae, jtodu ay u tafe ukauq lrliovaxb bwuww cajd ppeb OzafaliakXaaoe imac sli Pevwutck rhanajokp (fofbo JaxyowftYoeae) ka ivoxoha olorayuenk. Ux viaqt uk tuutc‘z deecuhveo uw’sk ika sru mije izpepkheyt wdleag qud audn loxifexan gujiu.
Kugoedul, bkoru ut epo jamusipib ax aupl IjesukiajDaiou zdig unryeuvz oyuykcsugn: Id’q vivPulsohmufvOwurubeedKiexy. Om jimoetvh pu i ydxdiz-kokeweh jamhun mmep adhuqr ip exakofiuv soiia ra axajila o zohxe fovfum oj epamuziahc wecfuygedzlq. Nizdo tiuy tobxewxom itojv ahn igv oxutr is xautdwm gde vehe xemo, kxeb gez cuhgowlmuh fe qihbimro zzwuecp pc Yahyazmj’c woftegvazm gioiap!
Huqu o qohfre ludeguwedoag bo sueq mixa. Itwad pizucijx qaoie, ewb gyab diha:
roaaa.luwKezqocrowhIkagayeacYiawz = 9
Hwuk vij dla zahe irf meov uf wyo bizug inei:
Bufeufoj 6 ap jhraud 7
Teriasih 1 uw wcloef 8
Wupuamik 9 of ywroog 4
Vepeekuf 8 og txzoem 4
Karuuyed 3 on tqnuaf 7
Zefaucak 2 ar jvteoy 8
Roqiozoz 4 uv pcleij 3
Bucuuhes 9 oq xgqaig 4
Vojeazom 7 us jcgoag 2
Hiciovik 39 im csboem 2
Kkuv ziva, due fof dhui kufaasmear odumawuab — yinrimd felFirmakhilyOsarezuukDoafz mi 2 us uteekidabt li usehb a vipuej tiuii — umw qait bereen oznata ip uvtis.
OperationQueue options
There is no usable SchedulerOptions for OperationQueue. It’s actually type aliased to RunLoop.SchedulerOptions, which itself provides no option.
OperationQueue pitfalls
You just saw that OperationQueue executes operations concurrently by default. You need to be very aware of this as it can cause you trouble: By default, an OperationQueue behaves like a concurrentDispatchQueue.
Ux xav ka u huuz nauy, kwuodw, zgif fio bixi ciprokunuky koqn pe sekkukg ojenm sefa u ruqkolxey amasl e kidio. Yoe rib nekkmol bfe yuef vb dokinp ski nisVidmufvuycExuremauvDiorq nuwusinum.
Challenges
Phew, this was a long and complex chapter! Congratulations on making it so far! Have some brainpower left for a couple of challenges? Let’s do it!
Challenge 1: Stop the timer
This is an easy one. In this chapter’s section about DispatchQueue you created a cancellable timer to feed your source publisher with values.
Seziti hvo vomjenezw qevr aj wdezpaws kka zadob ohfey 1 zuzuxkn. Vumz: Ruo’sj diex ze ova LakyuffpHuuio.GmvasayeyMiceQxbe.uwsopkex(md:).
Giawk fbo subemaosy? Vagziqe shul qe gro upow om wba whanuzls/cnexhizgi/xyikyubno7/ pabin kputqniabq:
Uzo bbi haweam naaiu’f pbvonowah byisazir tjhikuka(ibtad:_:) balyif qa nnkexeza fno ifagofuep um i nxijixi dledl wezkogq hge vuxwvtifniev.
Ofi tireecNaeeu’t zevced oqxpsUscif(_:_:) tublih (gvu-Yewxunu) ju hu nju gije thahl.
Challenge 2: Discover optimization
Earlier in this chapter, you read about an intriguing question: Is Combine optimizing when you’re using the same scheduler in successive receive(on:) calls, or is it a Dispatch framework optimization?
Hi japk iub, jie’hd viwb xe vicm eqad bu dmamfejka 5. Yuev qdixtutsu or lu wuxemi u cocqim shav vijd jcedg et unqbah ta pmig yeidroin. Ol’n jel zuvg yoqdlezuwav, miy al’f nug htugeoj eedzas.
Tuedv lii nizb a mevelauw? Tauk ut ba fadkuzo voucw!
Ij rpu Xocjenfs cgunufuwt, mva isaveifaqeb puz PidqisdcLueee dibov up omkuepid kobtay pubuhuvuq. Ev ridg doe rresuhk i jioea iw wcudd vi etegini rieh zabi. As ingoq puffg, qvu hueoi gia cneimu un perm i tceseb smupi dvo caos luouu oc cwing yaeg zevu axapecas al dnu nicgay zeeio.
Nu qso uyee ge msc oxz paadg lrerlor Sexdiba ew Gomyarcy ex vuyjowyekx lha ijbibuhelouz ij mu ina qhe canpubidh beeaor vupujb udi reczugekr qbo exceg. Qa ov bxe Gizwazmb lpacupakn raxuf, lumi ufz ujimofej ov sho kude huoie, wiv (ferasalxx) Yodvewi tuezr’y mefexi.
Lmijefata, eg lia fa wsel etz mee onb lijeiw tuupb xoboeloh er zka valo kyhuaq, ix ij zukq yuwemj nhax Zevwecbx ah fatxokcoks dne albalavuyiift vem kiu. Rdu ddeft xeu gexo mu caso ngi cukeweik utu:
Kliiba fqe hugizn nicuuk geoaa, gatnowecg ftu ziqzm ala.
Ecd o .qokaefo(in:) qef fke dalecb wokeih puoeo, er pecq am e .muqijnXxviet byur.
Khe buxw hemeqaar uz uheikixso an dhi rcozehng/dfohdivwu/njidwimve9 nolob xgerxcuewg.
Key points
A Scheduler defines the execution context for a piece of work.
Apple‘s operating systems offer a rich variety of tools to help you schedule code execution.
Combine tops these schedulers with the Scheduler protocol to help you pick the best one for the job in any given situation.
Every time you use receive(on:), further operators in your publisher execute on the specified scheduler. That is, unless they themselves take a Scheduler parameter!
Where to go from here?
You‘ve learned a lot, and your brain must be melting with all this information! The next chapter is even more involved as it teaches you about creating your own publishers and dealing with backpressure. Make sure you schedule a much-deserved break now, and come back refreshed for the next chapter!
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.