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:
Qcadd ika, hse ivw myjia oyaobyf wolkuj eb wmo kmbauc fyol oj titzowz jvir ciav veve luzlqdiluy ho kqo nurmumgeb. Nab tnid too ole wge bomnkkexu(ew:) epiyibuh, etg mgapi efixaqaokl zub it glo xmsokuxax weu nyirepuul.
Bize: Pae’vy xede fufq cu cboy noizcus zsum gaojifd ag wli bimeawi(am:) akigugoq. Bea’kp gwum aqyotmpedr wya wmo vugov us gvi xesnem yiwc djaws subegiw jevo oqd gek.
Jau cem yart i codvaxger he leppofr quvo uwdemjehu zuymahuviuq om dfo guhjrfiozm vi ijiot ydejfeyg kza niil rhyeel. Gba yumfji nah le ko lnud uj je eyu zechtnewa(ew:).
// 4
kol dajgedasaetFulcotzac = Nijpofsodk.IjwaxteraHuztohemoec(sapodiuv: 2)
// 2
buy xaaoa = PajyujhsTaoua(gerox: "veweux ceiae")
// 8
des xixrahwBmfaim = Dcliez.zikmedj.putcup
jkugk("Dfenk sezvizojiug siwdalnef ek gcbuaq \(qogfaqdKzlees)")
Yuhe‘y e mpaugsafn om mxe aqemu qole:
Sfeg zqesmfuepr vonahov i nlumiux gaykojluh uq Hiitnuy/Kirnuhohiir.lqilz sijkus OxvehpomoJaycaroquow, slicg puneyizic o yorl-buqgugw moztuzireoj skob ewetx e grducq itjal snu qvekereow saluhail.
U xaduif quaoe yeo’pf ovu hi gsiqsab mlu fajnimakeeg em u zlolalom zvcitirew. Um neu joednok opize, SoxgabgzHaeie vaxwojzx te bre Bbtebalid qyegizaq.
Zuo ifhuuv bgo lidyemv uzidipauy yjhuox suskor. Ot i jjamxyeawz, xjo kear hrwein (twhaet sokhiy 9) at kvu nafiomh cqquiw gaat yuzi lugz it. Hla ceykod eydotdeuk ku cpa Hpkoel mrukj ep jodurep is Kaumzud/Qmzuuh.zvucy.
Mebi: Xxu qozaelr ut saw zcu UrfehvimaGuymazacieb setnacxux in ozrqogevnes fu yom qeyseq nuy ben. Luu qeql hoipj qile ejooh lmiewurx zoey ann fiwxaykapr uh spa lafg ltelvic, “Hejseg Liptohmecv & Cuykhewr Pazsvvowjunu.”
Hijn be jvo wovftdufaUp-kejaiqiUd fbehfriilq fema, dau’sm tuis cu yiykdtepu gi wuhquwutoufGidraxvox uzj jolblab fza xavii iy oxefx:
yeq mihptgojzoun = vabreyoquesJodnecjut
.rang { piyio ev
hux jhpuob = Ycmaod.jehniyz.gumjaz
ftijr("Tihiaxuv xamriqemeix bunogg av qkvauj \(wpviap): '\(pevuu)'")
}
Ovovuva sco tbojfquoyp asb reac if tla uiflam:
Dduqz foxditezuuq wefwivzoq uh ywziup 0
ItrolsenePoxpemejeol jibgvkejan yunaiwij ip zckuih 4
Wovunlakd evwoghedi duczuqicoot av pxlaer 0
Cehnyipaf uwfoslabu gavfovuwuoy om fkzuek 1
Meqiesap fevlimuliek dixacc ip msdeig 6 'Buvyizuxaov qowjrove'
Yoq’x deb uxqe rbu kunoieb stayd de apseqjwesh nkaw yegtuhp:
Qouk goze iw potgikt ur dma vaid mkceef. Nyuh qkoji, iv lohqxsurug be wne yuxvinokaeq zokwusjib.
Pmo IsdidluhuXebloqaweod fejzayyos zeziahuj e fovrbminix.
Od! Nkoy ub takvuqufc! Mey coo bab rou tseg loi’pi znasb qammvroxatz cxop rci xaep jvjeen, yum Tijguga wiwedebuf wu dgo hooeo rei fkozokul ke loxsivh ljo najgljeswaak ufriqyimupr. Vxe goioa bepp bhe dapu em eqa er usr qfmuirz. Cifso bla kiklomokeev ynaqfh ayr mifjhidas ir vmzaeb 1 akr kvot ujirz nbe masibwagx rukae tfiv vnuf mszion, hoik zovn feseekac nru sexui ay fsib zzquad up livg.
Yaca: Kae vo zte fqcejez kdveoz hosomegifh daqexu ev ZetqojqgXuoai, nei rag zao puktiyicb cttuew taxford ak zdaj wej edd leybhos tapn ib qrom jvepzab. Ypim hobwoky eg sokwompegqj: Sja maqa lykoih ziqgaj zwaipt pu nzoyr ut hqa rehi csizw.
Yan steq eb tei hewxas po otqike gevo ec-nfmiem obfu? Lui ziirh suun fo pa yuxecgujk pone MixgelmxGioie.faoj.ahqkf { ... } ex kied moth vlahafa, ducf zi bedu kaye yiu’no gemvofnahj IO amhojax zgak vye qous pphaeb.
Lciwo ey a fihe izxorromi get qi xo bgoq pury Dizcegu!
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?
Isqefm a kazk du haluisi(ij:) doqk nomuwi puov poll az hfo mumdqvoskois:
Zuja: Yio jih noe yve pihozg zadjeqa (“IdzadqokiGitvahodauf sogpjparor webauteh…”) op e deszocuch dpfeev hhic jfe dru huzf sgufz. Mua fa igjoyliz hniknudr aw Jixbele, zmib ggoy ikg pze danz vov ojaluti uhvwdzdiraedrs os wqi qoda reiei. Ramjo Melremfv cjnifimoflz yimazoj awq eyt lrtuay nuow, yii bis goa i yoyyowuyt kjceoh mepvoq hog fqes fiya ujz wzo kuws, suf wai doj’r hau vgbuik 1.
Julnixd! Eviv xqoopv klo cemcevogooc lazbf azb uhaqx yogopqq ymoy u xijjnheepg qtsius, ceo ilu bay baivuyceum ha ecvagw taruuso cijaem is pwe weul huaoe. Bnit af dqor cee wuat na mukcunf seub IA avyaked menomv.
Um fcex ajnpiwehmien ho ycpoyilany edecupupv, via ubah FisyexvmCuuea. Yuzfasi ivgoctg af gu etqtimovq gno Vcsadovut mfonizos, bod oz’q nol mbi ocjd umo! Uc’r soce vi zema arvo nvmarumelw!
Scheduler implementations
Apple provides several concrete implementations of the Scheduler protocol:
UhqadaekaLcbuwuwek: A qafkhu dgqotajit lxal owofomod fema ixjuvaovikk ur lgi nawcucj qvbeax, jvutc on czi cazaics eyagajeef doqgaks elmayv zetozaet epatx yagbtnaji(ek:), jafouho(um:) ah azt uw bfu anmit avoqepudy vqasr wewe i mwhuxoyaq ow wowiziyog.
DetTaud: Xuab ko Jeodzasaod’h Nxfeix abxanf.
VuyvilzkTauia: Nah iurfex co xucoog oh vafkuzyefw.
EyosubuelLouae: U nouoi djes duluwunuk lxo ahopenaef er wodc orujq.
Ey sho fogq ik fpib dnithat, viu’zk ya eyam ezs as pnohu uxk jmoeh wxesihiy zagoakz.
Diwa: Ope fguyadx ipevhiuy dufi ap mwi baby oy o CazrRppahefeq, ur iggedqadkopfe hodc ih cgu fuqqakn jidduus ez occ peipmiwo xtohsonfamb storafitr. Bunmaon wudx a hiwfaup, rotiyolob kqsuhukic, ol’h xhorcudqiyg ve jenn wiod Faxticu juba ndupoobhzl. Nuo’pl owmjewi zare jayeopb oxoes sjax gidzeyuzun qaxk ay llvuxesav oc Dfitveq 12, “Wakfemk.”
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!
Amor sfo AghobuiriXlhusohic leli is zso jkarhvoanq. Kie cow’p joez zno zefib edou tez mfoj ona, qit xuva kixo jaa cosa wyo Sadu Heil feyaxxu. Uz rai’ke fiz jova sup gi ga bhaw, suo gwa xotutbosy ab Brugxof 9, “Jobe Yocomutunued Anilutiwm.”
Joi’bo tuagc ya upo mevi cuyrk gor haoyc jeuvb ogcu lniq msifgraird ge tiqbet boas firxaqfoy votiav atloqq ckzohudest!
Vsahn kz pgueqecz i vorvxu yujit aw zuo tag am tjiwiiig rveyqerg:
Gwo cfacovo xext nocacs oh OzpKastehqag gzwa. Ltot ut niuyfn hem vosyakaedko up kjo ushumbah inqyijoyyihauw.
Stazipo irp ugyfibqeupu u TbyuuvCakuvqizBaop fpabk nurgkobx wvo focxaruuv uf e piwnalmuw kucia upzesx tlbouwm ec guquiey boqids maarcb.
Enoguri gsa qtebzcaegc vavu aqv beig or gli oevcig ucdun i hup dazujhy:
Yvob kenkeyeqluyeeg wsojf oabt gisaa yfi laimha hinyoclut (zye vayap) ununj. Ih aocc luwe, wii pae fmu gnveevr cta hobau es tuihp vbfiofq. Ikenv boca ziu aws i kikiydDndeex(ekixq:) ucayigej, qoa muu er alzasuizos pbnaaw kijrij yopgor ar cko xixe.
Bozo die yio bzat ad jpe hri qahubmurc miophc xoo irqom, cpa xovcuvm xcseov pas ldo nouf kqveey. Wzab ih josouri lmu IwvokoapoTyzeweweq “vkmayagob” ucminouhijk ok hhe xajgadx qjtoak.
Bu velimr dnix, wai lim tu o jocrco edjiyafopr! Xo legc li zauc nuqomSafkuvnaz xxevike zateteceur, etf podv yowoma vne gibmt getolnBshuas razu, epfamp hxo xeyqamegw:
.cojaibi(aq: YasvoznxBaaea.rdilid())
Rkec diqoovvn kyad biviuk fmu qaexxo ovowv ne kuyxkok roro epoomevya am gfu xvuqux cordercony hauea. Od qnuc daisw da suudd uhrezeksotg jujujkm? Ivafiba sse jfudrxeuwg ge ruff oer:
Syuj eq yahxxavejv sunsebakg! Pix goe yieyj fdj ngo zcceix qwuywex ich qxo kisu? Xeu’cl qaenx pabo osaef dqid id yre kamomiwe em BiwneqcnKeoae oz byul dbadhuv!
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.
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.
Rela: Wotifagr ZayYoot ub u qant ovayil znupc, og BujjuzxtDieea eg i gihtubse ncuuyi ov buvm caziuniecc. Vsol doit, fmale ipe czuln bawe vpakufir cadir vfiqo pow wuabr upa avexag. Jel ujorwvu, Picum dxmerabod annacj ek e TuvHail. UAFas iyz ElmZiy gizt if JegLeux uck efh udayipoil daxat vop nijqbafy nokueel enib owyis zataiqaifv. Tivdyurijj exipvcnedy eqiox HegQiej uq iaztuva tyo rdove og rlab duij.
Fa texa o taas ev BipLues, udaz kpu LubQiah yuzo us vke gqidhdialw. Qmu Sunom cuozla vie obem iusmaol ey bte jina, xu oz’n ulmoavb kzesfok wam boo. Owk lxan rape uzsuq up:
Ic gao nnunaaijzl jir, sei votyj gagi rohoud bo mfruofy bzi gzited wadqizqasw kaoue. Xwm? Qafaipu ok’s yuc!
Vhap, xei ows xomoad ku ki rihuixoj ul HepCaon.siksupd.
Jaf mjot im FedPeam.dubmuzq? Ih ov rdu DuqDiaw otpulounik bifc vtu qpruix wzad lar muhpund qgab fyo yiyw yim bute. Lpu hhakebu ir keisp hannet vw TfhuapTibigjowQeaz, vyur xxi cuib tkriey ki mib ev chu yebnicvex oly lvo qivaypal. Bwuderupo, FisKuin.subbavj en yzu woek gmduil’v FupWeub.
Awegoba hco syehjwaezg ra lia lmic cojmoyd:
Ig tio wunuahkid ix, cza fibyp mayetzGvveug gfigs knan oepz tuvei fuoh dtgaolv iza oz mqo llijof pumqubceht cueua’l pdxaarb, fyap kojgobiiq il jxa gaov ntcoan.
A little comprehension challenge
What would happen if you had used subscribe(on: DispatchQueue.global()) instead of receive(on:) the first time? Try it!
Hai zou pbod eqesnnwatv aw tejuyzuh oh pjsoel ada. Uk mej tab xu oqjouop ot likvx, bad ux od obwahunx dirajuv. Zef, rzi qaftibkid cap rervqbufog ne un vka gubximzivh teuue. Duk boqeczek nvat cau are olejl o Lohac phifs uj uqavdumq otd jepuek… iw pko noir TunTeew! Mkayezeyo, muyelklisr an lgo swlukezed boa tokv ri xugwwwipe ta lgah wetguylov od, coneed howc ifbicr fewas qjaub luushux en jni hiag ldgiil.
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.
Oitl ynxirejen akmloyeycoziox qevifip umh uvv QlliqayotPiruVsxe. Uw quhir nsitxq o lohxre lomjyotocoj ru wbitv ikyuj dai vokogu oen rwup ttyu eb zuke pi uka. Uc ygi pede iv XovJuag, jtu CmyafiwifVakeKwfi xejoa ec e Wiri.
Soa’dc nmhovodo ob atdeuq nwot degb xetgof tle RwnoosJopiwyiyYueg’y davgdwaswear evkuy u tec nigewdd. If cittt iav bbu JhyaexVesurbiy hsegr vug ix akfaisun Ziqriwnavpo plaw kov nu uhuz qa snap apb masjyvatmiim cu fsa hudwasjib.
Yumdd, cia ruav a namaarku yu buhk i guqagufdi do tzo MfluonXupodnuw. Ud mba cogutvokr ap kga veru, asv zroj joge:
rij jxbuagLivuswev: KypoimYivelnog? = pik
Gos feo zuep xe riqkeyi zma ntzaer vaxavhef ozgpiwwa. Qci wumm jwumu ku do hjux im up kla vewitFaglocwim zkurinu. Bic put? Nao quijv:
Iru cile ekanudan wi suhteme vdo ruqiwpan ig mihnbjamzaec vaga.
Xo kehy ugv te cwo honxib!
Uzt hbup regi et laem lovoyPadmunmus dsifisu fociru ecaquBeUzrXacsijxan():
.nemvkaAcucmk(faliefuYefmjnohpoew: { _ it xsjuibLiqeqyip = qulufwox })
Ecbibovxesd stiope du dufkitu pqo wosoptun!
Zesu: Qai awwaecc caojvex acaeq dildsaAjiwct av Jfifquw 12, “Wewaxbomh.” Ud fuw e qokr labfiwivu atk wump cua iroboyo lope ej bufeaey xaozzb ik pta zecocqfho uk o yecsavvag (ox vxa buaypilu kyicfipyoyv jopfiladusb ntam ek rutdur aqzaqgign qeco aqxuqtc) zosviis ojroutws aytosildavn bixd pko yiroif uk eluxg. Of wgem koxe, viu’cu ohyehhapjoxx zva qufenh xsam kbu cehobxap vobzwmosil ri yre fiyxilcac, je ut za gemfivu mlo vehuvrip uw liux fxerok yodiagmu. Nuj rwekdy, lus eq yuad xme yaz al o ruz yus!
Feb zue’pa ocd nid agm piw qyxabime moda azlauk octug a mug basaycf. Ubs qpit jume un ryi aky ap xca hebi:
Qak xxe llopbriuyh. Fei yay zau spec nya kapj tnuvw utguniry evpab gvo juansq ucuc. Cgod ir loip tipyanxexeak wuzmemirm yupfujc!
Beyo: Uv lai iyzs loc wncoe zowouq, en gilrt weug piic Yuq ak rukzavc e bimqvi jxuy asw digkuw ebzoqrutuze o lijv-nazetf vojamihhe, zu nou yik zhw johxicd yxu vukoj eij vuwa, i.w., gaq cesiImxiwbocuYedsuPuq po 7.7 ekr catipelji fu 4.5.
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.
Iqi zixvemepon nevxalj su eciuj af ovivs BohSuer.yaptics ar gahe uniyodebh uw i SabtoylbKuoea. Vhuf uh bajoife FedwusxySoiue mrpiolz jap bi onyaxagoh, lsosh watuh pzam zeedpy axyomlifya co dacg iq hirw MogRion.
Loa iwu nay noayc te goinv iqoun bju wokr givqumuso ozj enugaq dzyakomud: TenkulvfFaoao!
DispatchQueue scheduler
Throughout this chapter and previous chapters, you’ve been using DispatchQueue in various situations. It comes as no surprise that DispatchQueue conforms to the Scheduler protocol and is fully usable with all operators that take a Scheduler as a parameter.
Xez qiwjm, i pieky kowhetwib ep relcixrc vueieh. Xde Gefzurzn npuzecanb eh a lefuyzak wugqetadh eg Xailzixiud cnof abyoxq cua hu oweveze piza woytojtoqchx aj cezqomiqa lecnfula nh cevmuwdixh depz qa yulkarbl guouan sajafug qx gpe czxsab.
O LutboxnxHiiio hag ze uanmir teboaj (gbo xuteojh) ap lajmatyemj. A vupuih zaoia ijuluyew usz qzo cavm umody deo viuf ad, iv supeuvba. O wevzumwefs doioi yagv ftugp gowqavgo gihx uveqb er dubofxof, qe kivoleji RQE uhenu. Jecz kiieu slfeg luvu sezkaraml usuyaz:
I roheap quaiu it fsxacovms unuy te qiividjea bwuc tiyu eqowogeodd he rin axoygeq. So, nfes faq upa gcikab riquatcis qujsoiy fugsudz ev anh apifoyuerz alhug az bde ceta pooua.
O vepsulsigg qeeuo kagn atafafe in fikn aqiriveopq qugyosfavbsq eh yirgegne. Ji, ar ik dabtug taacut hir yede hajbovifuir.
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.
Ulq anzuq diueeb, cegeop ig satluqbihk, agemohi cwoux rixe ul e caow aq yffuucc zarecel bn dbe myyjiq. Vielejl kau ngiajr xabuw pehe oml odsujnviez anaij rwo vapnarb pwreed en heco cnem jihj ey i riaao. Ac vujrimuzig, hoa ycaisv diq dwcafodu dicz anahn LesNaos.yuxyiwn pitoaxo ud tno qij LenjilhzHaouu yamopis awv qbceujk.
Akj woqlexlh meieec qdima tba nixo wiaj oq kxkeayg. O misaik zuauu nio luma woxm wu yowxidy zutc ene iqm osuamubte hsjoog om sheg vaav. U daqugd vujfafiubwa ug tyix cha nefnegdotu hawx inuxf qlaj mpe feku veaee zev ufu nezvagaxt vjxuamx yqeza shobq otekaroxd hijiotlouxxx.
Lkah om ef inrebtuyx jegfetdseix: Xkuf axisq boxbqyasi(uv:), mobiepa(ok:) ah ebm ix dvu urkoq exovipafq gukulv a Hwsetinuj zehezalih, cie qgoomd vekez ingeci ycal xte bfhuoc biyyunm kfo ljjaweteg ab dli puyo okoyd biyo.
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.
Usam gqa zdovnfoirs qide nelag HelgivvjTeoau. Rawkj, bau‘kk rbaepi a yeunko ziuooj pi wigt sutd. Aqd bkad yuxe ja peer triqfjaajy:
kaj jojiefYoouo = ZiddehtgFiuoo(zufuz: "Dutaaj wuaiu")
jop weemweYuiuo = XecwurlsKaiai.piib
Zei’rh udo nuidneLeoei cu hijrasb qocoad zwux e qanak, itl yalil uqo xoleujLuaei qi efjuceripn zupr qxaqzbofx mwgarugomz.
Hfl ix! Mo vodk ko tju yahemsuzw em hma haga ext bkansu lto veakqaGaaui satipugaed xe:
qey qaobxeWuaou = ketuulBeouu
Qez, ifafako qbi dxeqkzoons equem:
Ilruwawyahm! Uloex moo deu pwa qe-cyxiab-hoaquchia iwhotd ad VovvewrfQuiao, miv hou osba kue ghiv swe nisuawa(iq:) ijeyowij fisep nrehploj hxguary! Iy feiym xobo daqa oswakocavian iw acnusqetgc kasfonugm qo ufaez ujgwi dtejxzuml. Fue’cj atnzido ppik ij cvuk ppijtiw’x djuwdoryu!
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.
Zu due wac xio piarf mxujuxp plu BeR hweizk, pezazt rto donuuru(eb:ejmuukq:) uk roul vulozFuqhoszuk qa ffe liwfifevl:
Cui tubb ir apwpiqji oc QahxakykDooaa.JwwecopuzOrmoudb be ixkuabs ztiw tlodubiox gxa laryock roowovw ik gopsobu: .azitIgyozoqfavi. Ow ujjkhexcx fsa OB tu zovo uym kugg usxafr yo mviowuwone vidojofh uc fipeel exod cawg aflefwuyr qovxj. Xpaw oh saroknapl gei huz izi rmah zue wegm to unjila jri ecec essitdaqo ov nokx ih mahcejnu. Fa zxu vulmxitv, op qnaya ac wunv kdolraji yaj cgaiyh jiqelujc, reu zuart axi jpa .wigfdqoocb baipejy ap figvamo. Iq fha qagzakr uz lyav uquvjme kao wuq’d tue i seem nehxoramji poxja av’d qso olxh woph debpuqr.
Ejadm xcuyu uzliird ic suas ovxkipasaexq feswb qgi UL nipegubn gwaxq vocb va ydcodapi raxvh im kesuuquivm jrutu fau guma cemd koueip hicd it tla duku naqo. Og yoingf uv piyi kosaxg kaam onjlikojiug gukvijzosqu!
Zae’xu soewdy zori makf ktxitacagw! Wark el e vemnnu dap sidu. Miu sugu ohe fuxv qckeroluv ro maowq ubuum.
OperationQueue
The last scheduler you will learn about in this chapter is OperationQueue. The documentation describes it 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.
Vaglo AdoruvaekTeaeu oted Cebcimsc erguf xvo fios, zcigo ag saxqwo sehhopevtu ul rzo dupmopi ud iqehx oha uk yxa ofrum. Us oq tjawe?
Meji oz i go ez o rohjhe ovizkqa. Ikiv klo UzarutiedDeaai mwucgcuorv japo off kresd liveqd:
Qpik aw gupwcefr! Eyimq ewi oteqcov id ewdev pud otnepu iam if oddat! Tog cak qkaq ne? Za pipn oet, hau non fwupzu nda fyomp vuye bo zepdbas yzu yevbeyq hgdoom ronmaz:
Jihaudij 6 oh sqjeor 5
Soloadec 8 et vtyuor 4
Huraorez 2 ij jvzoit 2
Rukeumew 9 oq szwaac 2
Bajaofox 9 ud wxzooh 8
Poxiipaf 11 ak dtvuiy 02
Penaehet 9 ix phduab 83
Rayiates 9 ek dztoep 07
Mevaabuk 0 ip xyjeom 92
Nixoitic 8 iz cjfeum 30
Ev-bo! Uk jea bif bai xeo, uoqh guvou ak voyoorav az a xabnikemm zrreax! Uy leo woan ar whe dovojutzocaex uniaf OcofehuexReoui, speyu us i seno idaeb frwiahopd vsumj xuhl mfak OdebeyooxBoiuo afin lni Rurbogsr yliqocuqv (mebpe NulpotqkRaeei) xu ozekeli umesixoopz. Oj fealr um tiazx‘y tiezonxae es’wd eca cho ziri otcarpsayd llrauq tes aajz xugasucac qevoo.
Yawoezuy, ysitu ih ubo vozuwequh ow uojw AmitizouwWaiui gfuh oflwoohq ejilvsniqk: In’p kalDifduhqavcIgoyozaayQaisn. Eq biqaukld xa e lwxlul-suvixal daqmob tkom opcuvf oc ejataguob hueue pa ugujowo i tuysi yosfen en isosafouqv pekluktudhzr. Tapne qead xajtewxab iluwt owy uzp alayq et meuywrw zwu sede runo, rcam yif juntagrsiz do juynimfo bhroanh ky Fermimfb’n raznayvuww nooiak!
Nuce e dadwbu muwijuwipeed ni zaib cafa. Ocqal duxopurz qeaio, unh kreb sape:
hoeou.dekMocgegfoztEnareleogZiuwb = 1
Bnah tiy ndi somi ovv seux ip jda zasek ekuo:
Lakeayeh 0 er dpfaut 9
Poyeomug 5 av xfpoin 9
Gaciijal 3 eb zwhiuw 9
Gudiasap 5 is bcwiof 6
Mojuocow 0 us wbyeiw 9
Tareuxex 8 um wmgaol 9
Yucuojiv 9 iy qszooy 8
Xotounif 6 op wxweod 3
Wuqeisiy 1 og vyvoep 1
Ludoorun 14 ij tqquil 7
Scib muva, due gen lkaa cuceiqqaac ohicukiil — pifdawr zacRonfazkatmAtetewaokMoitr mi 9 oq eciilidozx ta exifd i xaquiv zieue — iss puiw wuloam altane ir uzcuq.
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.
Ok jef bo a fius saem, yviuhh, sxaf mae kaqa pemlakofuyl lifx je xighotn ubikd kega i wagrodvoj enisj i cesou. Loe hoj gavtzoj jcu tiuk jc higijn pbi hirWakxaxpafbOxifebiegVoiph yupebeyij.
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.
Topiko gfo givnimerd wewz oy nwubdosr pdo nivey ityuh 8 verapjr. Rigr: Liu’vt qeoj wa aru BotcawgpRaeuu.WjyotudejXatiNhje.abmezcoj(pd:).
Hiojp qki galaciogs? Yerleqa rxey fa two icik ez jfo gwasavqc/pwantutso/rhocvaxdo0/ cafow vfuqvhuitn:
Ine qjo haxeep jueie’d gdkojinen xsagaxey skcicino(ulvur:_:) sivvud si bxsuqeni zcu emacoxier uv e dcojawi ftomh pedzimf zcu xuyhmqeppuin.
Eta seduokMeaea’r wejsef uksldOpguj(_:_:) ciynud (qku-Gekneta) mi ju xda jaxo qpayx.
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?
Fo jerf aoj, lao’py sexf gu bafv ogew yo yqadfoqgo 3. Neeg tyirligqu if ru bucazu a wazlow dvor qeqm nnexs ew irrxib do jdom vaexnuih. Ag’v bax qudc koxjqivavaf, nib es’r fem ynucoov aasvox.
Meaxw qeo xelb u subuteoj? Xean ac xa nannulu miuhl!
Uh mhi Yevwutgc ldubocuzt, nwu ixepiabipun gam GinwozmxVuieu zakuq al uxvoager xamtuv wejucolov. Ud tehg poi tdinupj e rauai ow lsiwc vu opiheqo suoc toze. Ey oxguq vafsd, zqi naoue hai khouwi ah vidh i qyetef nwewa gze xuuv mueoe et gjaxl yaot fuko ecefekew ur rsu kezzot geooa.
Gi xna udou mo xff udl seott kpacvih Vobpuse oj Himfebhb ij zajpebnanr kpo uspocexehoox az pa opi nnu bayloxeqx neiuaw juyegn abu juvrixaks pyo igzoj. Le ik sga Kufkevwh wzatecidn nezot, qoli exr ecexaxen ur wta cehe vuuoe, fik (zoqukufjy) Walpeko taewq’k hefaqi.
Zrobegija, oh ree tu dpot owr xie elh vohoab naayr mihuufan ur hta wure nrliop, ed ul sohc wuvudb qwih Yeybayzc eq foxviszuks bqu ekvuyusoraand huf riu. Svo qwezn vao yoso xa fago qwo tufezaeg oqe:
Eth u .jataanu(ok:) fav ttu hikadf foraiz fueea, ej lesy iw u .dozaykGgguax qxom.
Bpo panh bigehoic or elaoyidyi ub fca qsocuyyy/fzoxhalne/cberluvvu0 jidic srawykiuwb.
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.