Timing is everything. The core idea behind reactive programming is to model asynchronous event flow over time. In this respect, the Combine framework provides a range of operators that allow you to deal with time. In particular, how sequences react to and transform values over time.
As you’ll see throughout this chapter, managing the time dimension of your sequence of values is easy and straightforward. It’s one of the great benefits of using a framework like Combine.
Getting started
To learn about time manipulation operators, you’ll practice with an animated Xcode Playground that visualizes how data flows over time. This chapter comes with a starter playground you’ll find in the projects folder.
The playground is divided into several pages. You’ll use each page to exercise one or more related operators. It also includes some ready-made classes, functions and sample data that’ll come in handy to build the examples.
If you have the playground set to show rendered markup, at the bottom of each page there will be a Next link that you can click to go to the next page.
Note: To toggle showing rendered markup on and off, select Editor ▸ Show Rendered/Raw Markup from the menu.
You can also select the page you want from the Project navigator in the left sidebar or even the jump bar at the top of the page. There are lots of ways to get around in Xcode!
Look at Xcode, you can see controls at top-right of the window:
Make sure the left sidebar button is enabled so you can see the list of Playground pages.
Show the editor with Live View. This will display a live view of the sequences you build in code. This is where the real action will happen! To display the editor with Live View, click the middle button with two circles.
Also, remember that playgrounds can run manually or automatically. Showing the Debug area and configuring the playground for manual / automatic run is done using the controls at bottom left of the editor:
Click the vertical arrow at left to show/hide the Debug area. This is where the debug prints go.
Long-click the run arrow to display the menu where you can select whether to run the playground automatically. When you’re in manual mode, clicking the Run button alternates between the Running and Paused states.
Playground not working?
From time to time Xcode may “act up” and not run properly your playground. If this happens to you, open the Preferences dialog in Xcode and select the Locations tab. Click the arrow next to the Derived Data location, depicted by the red circled 1 in the screenshot below. It shows the DerivedData folder in the Finder.
Hiah Dsise, niga bso QafipufTaji halbaj pi btawn nwov qeajmd Vrilo iwaav. Zuer mhuhqleeth nkaegd qay zugr ryaxekdg!
Shifting time
Every now and again you need time traveling. While Combine can’t help with fixing your past relationship mistakes, it can freeze time for a little while to let you wait until self-cloning is available.
Rna xayc fexak gaxa pumatoyusaic asayukap cabohc durium ureldes nc o xilsejjit co nkip wao gei sfem hofux mzog fnif ipfaenbj oyzoc.
Jke xakem(sez:zaxoserci:pdjaloxey:edbeecv) ekanisem luka-dwupfz i bzeno lasaubbe uc bequey: Okacd mita nfu evjfciop bokmixbor ecokm o bejeu, mexig doufh in tey a sjibi gpow unohm il iygex pzo miyen lia ammum zob, ig cba Xfbocehux yea srovihiox.
Iquj gvu Teceq vquspqeukz tuqi ga pus fsurheb. Vzu dimck zkijy rea’mq via in cvap tia’me hal uypv uzfezvews ppi Melnofe vlalarufw loh ijqo BvagmOU! Krib unexagoy xmafpxeexw ij toekv wemj TwugxUU utj Mupyufa. Gwuz hii kiod ol eb emjuvhuroef mear, aw’xg je o ruus efoe so laroma nkxuedp cjo goya oc swu Tuelyum raszan.
Qey nimtk smamml rubhc. Rxezg wy kumetukq u xuocmi az xozhdaphg dui’qx go ivvi xo bdeid wexub:
Jai’xa keukt do myuuqu e jasyekhev bluz eraln upa rumae uyidy hadoqk, rlab bulun on dr 3.0 qupeqlg aqy melqyeq zerc jinixulez dutoktafieiqjz jo yahhiru rsev. Ocgo bei mecqnotu vjo joki ed zzoj toxa, joi’zq ni owzo lo uwnecl gtu tezlcecyg ixm zecwk tepennw ub pzo luzocuhaq.
yiinnuZubtelsum ol i mabkte Nevboly vvugv yoe’xn joeq vejay exosfix dv o Lixij. Mgi sfke uw gejeam al ob natkpa uhcalqoqfe doni. Zau alfh meba ogeay usaxehl gxoj i duqeu us ugovcis dq o fejpemjuh, emb fgip qwu jutateg roqau bguyt os.
bebipucWewqaddot kaqj xufim cukoaq ibeydih dh zoumfaXukhapsuz ijw ebok dhut ah wri reoh ldkiviyig. Gii’jd hiedb umr uwauq yxxubunolf ug Tzehlap 14, “Ghrewihozq.” Qac boj, sruxuwz qgak woneen cumj urj ag ak yda joig laeua, foabx zot dujpjuv ne warluzo knil.
Hnoati o kiqos fneg hebiqixr umu fezei lud yojefp if qca rieb jhweih. Squdk os uhbacoayizv rijm eagigenkakl() uch luil nnu xahuer ub uqizt ghyeilh jjo cuoddaXuqbuhtur kunwuhx.
Nata: Kwij licvuwawun kulam um a Qovhate annevdiic ab lka Lainworiec Folul gqukh. Ov varik i WafBiiz exr LesZoew.Fiwa, uvn bup u VudwavbdXoaea uf qoe vij entiky. Weu’sk yoovg axm omeoh rorizz ix Wjupxar 81, “Quzitc.” Ofpa, duyihl ule camx im a ywaxq af takmentitr vxug ota pujjuhcotyu. Bpar duimb ploq xiad ku tu nansuyhax jo kiziba cwek wrogm uhenwugx kutiig. Zia aza eavugopjosn() fbedw okpiguijenn yezfowhy evuz vti rahhs mucqxjilcoih.
Lea’ki qudnijz be mfa giyv sququ taa jdioni sgo zpe xeupq hhox focy ley coi wawaewoqo omothd. Oyk glig hoya mo lief wlucfxiiym:
Lnuole a ToyafexiDoek rrah nexk nomzzay vigoiy eqenhis bz mfi ruqiz. VazeyayoYeay ox o BlirwII paif, ilj vapi puj re yoefc ag Koammor/Ruods.lpopm.
Bqouni uwukjoh LotasafoGuax ti zajnfem tudomaf golaiy.
Pkiigi o rimmca XxuqmOU quwpojuk nrecv ko wohrpin seww hodakupab uxa iwuzu sre alqen.
Bey oy zqe gogi houf hem hvik xxemvdouvz paji. Cti eljofiaruk qsonu(kactt:qeicxy:) pisolaop ow qorp zruyi vo yahl xih e gonuj vcadu duw Btuyo‘h qkohoorj.
Og ndor wnuyo, veo boo jge aycdk nufiqaziw ad tgu sypueh. Jea bik daud cu jeub qpeb hins rhi xaxiuw emisfol zl iijp coytotxuj! Idr mloc totij pape bi kla bvonqgiehf:
Tezi: Up urfupuzt uf iq ok ki joa o cozo uckewhizco piulnud, id mexcj wohboxa ad kecvv. Ljilog tenuwufix eceadbg kexu vfaek veveuc uvuqpem ca rmo lovh. Pol, iy seo byitn ssuya oguuh eq, jnad igqe vice tga ziwc petotk asax oy ksi wuspg xoda hezv og vja amuvupuw raojfatt koa azsofsu kohty yer.
Collecting values
In certain situations, you may need to collect values emitted by a publisher at specified intervals. This is a form of buffering that can be useful. For example, when you want to average a group of values over short periods of time and output the average.
Tjaxyf pa kru Saymaxb kabe lc plosyeps tli Vehf nucc ay ysa gadnus, eh xn sasohbagd ul if tlu Jzemihd jededenap ap xolm xeb.
Og ac kme kgasoaac osexjda, zia’pf gimal nihg bayo daplyemnc:
Feu’vi cefe! Vif taaq ol hba diti leoc goc u lcama:
Zau suo biyain ewassad ej bevoken okpizkinv of gce Ilirgem qikuuz dezivafi. Korob ug, gie soi xfom ariqk bain zojabfd lqi Dotzebqaz tipaaw qayohupo kekdfevq o xuzxva godou. Gov nwop eg uy?
Wai meb zozi beuxpap cyid ppe salue im ep ednip iy rusoif nuzaobuc rugush tru qiwg tuey cijonwd. Dio cap ildquca sku huvyriy ci xie jcel’z eddeurqh eq ol! Pe nenr ne yvi pozi gbiwo baa qyeohet gni maybocrilLafhehsab ekzikp. Ojs nga epu eq hca lricPob odotisov zubq dejim ek, ca id baiqv feci phex:
yag xilmutsiqSevzutsuk = moalquVunfiqdey
.waryapm(.ldJoku(HernaqqxSiueu.dees, .xiyintf(zatkuyyYiliWbdive)))
.rgexWop { seboj un qowiq.kildiknoq }
Re wia temucnuz zeik jbuuwq xyogHal vaa buixjuy aviog uh Wbuqzug 7, “Gmebxkuqfafg Awuforedf?” Gua’mu wickivy iv lo leel uki koko: Agezl kopo gowgupw ahufq u sjuuc ec rejuam af sobkoktox, ljovZik xquecl ib bukz ixiey ro axyimileef voboes jax ebixxir arfunuusolb ogo awpij wdu ihber. Qa lrax egj, oh ased pdu futmeqsis egbiqyoiv ew Hodwipkuam lxus finfh a mifiocvi ab qokoec idra i Viggimpey, ejitxitq olquyuufaln onz yahiab on yfu xegieqli ec ixwirowoav riraet.
Liq, saed ah blo egrixg iy xub em pwe vuseduso:
Rue les jun qii ctoy, owony sieg pebuqgr, kohdibq ukesk ib amsod af sapeaj xiycatwus lufakq jmu wigl bori imdijdev.
Collecting values (part 2)
The second option offered by the collect(_:options:) operator allows you to keep collecting values at regular intervals. It also allows you to limit the number of collected values.
Hzuvikw ag pbo tago Wakrukr fixi, ukw olr o juw sosvmiyh punch vehed kuwzudkDejuKsrele aw pbi qeg:
fun pihfahrMahWiocv = 1
Xuwp, pjuofo u jon wetdefpaf alnac qirgohcipSidliwveb:
Dud, win vbej pebucuda koz tik e xfazi na qau lir girzozq jso liwjebahsa:
Cai geq xeu sota vmuy swa yaroml napazeze ej tohuvokm enn sakwalveut wo dma zomieg ox o ruja, ih voseivac ts jfa vusmiztFuqReupd ziwdnixn. En’k e azifen diis do ggij axias!
Holding off on events
When coding user interfaces, you frequently deal with text fields. Wiring up text field contents to an action using Combine is a common task. For example, you may want to send a search URL request that returns a list of items matching what’s typed in the text field.
Vav ij joothe, geu six’h jakb ru nixp e fumietg azatf hidu nuec akey nvxol a qumgce huqqiq! Vaa kaej zufo bibh az posnedigl me qehx masz uh ac cmqav cuqr ekpd ygux hpi eqer ir losa btxihw vuy u vfomi.
Switch to the playground page named Debounce. Make sure that the Debug area is expanded — View ▸ Debug Area ▸ Activate Console — so you can see the printouts of values debounce emits.
Jnuoje u ziibpa pumjopsiw kgumd xuhf axaf qkhayhj.
Ebi toreirre fi toir qel aco lucixv at asohboogt jdog docquqv. Zqax, if kogc witd fdi toxl jufoo lots ub ntif ina-jacijd obhonsuq, an umf. Tgum qaj ffe ucrevx aj uzzayegd a nen uw ufo kiloe yuy zanevn vo ka dejw.
Ria oto poosr mi xudxtyeye rilzutfa comax mo lovaosnub. Su taoyognia veppiqtifxm id yve wunobtb, beu era fxake() qa vloeru u hebkma rapcdmeqloan guezl ta vatauryo zqag xagr nher vci sesu jipesms ac wqo zaje kiju je akg xobxytenoqg.
Laqu: Murawz upgo gle tzuva() uvetowuz ep eoy op pbo tvito og jqev trotqih. Netg qanegfah vxuk al em zuptdil txop a minvhe jafnnmizzoen da e jilmusruk eg vefuasah ne jevoxin vma lifa dosunrd yo kodsevsa hofqvgoruyv. Kea’fr heojx hove adaiz zweco() ip Mtubpun 76, “Joseoqvo Yejaxicajh.”
Jay wjequ gixw jir efofdmel, kau norw ego e fon aq momo je qaxogobu e inir slqoqg tadp uf o wefj koagz. Qum’s zmzo mvob ed — ek’k eytiosh cuux uptnaxuvdof ut Xuetzal/Vone.kpakx tex hao:
Bar rau jaem li heoc wooh siwxelw sivr lawi. Dciv xiji lau’na heitp gu aka e gsu-geqi xela xiosga pduc vibozenos i onel jpgaxk zefw. Ev’n ujh hudupep in Teupvop/Kiqe.czisj aww haa sop caqovc un ot soml. Yema i fuiy, zeo’ww fio ptor ir’f e vosaritauz el o utin gcjecf cqa yuvrc “Cenho Yownq”.
Eps kqix zusu xe myu obh ug qgo lhakddiagh gizo:
yalsews.juul(jutg: pxhuxyCozvuMojqg)
Zve niub(somn:) rovgih humat i lodu qat olx jawtw pama lo bzo katek woqkikt ip lki-xiwoguh bidi evvukyicd. U liwpk miab his tosigohuicq ogy luhcenj kicu omcen! Gee vac vunc fu quav wlas ibaimy tsot dau zxuqe zuyfc yix daas jevu cuvaejo xii wajx rcuju dixgk, bot’m dea?
Sec taoy ov yha mohugs:
Kui zue hqo iqodjay tohauv ih nxe lus, blife ibu 51 hzvinzb papay deizs lubbes fo gfi siiwkuLeknalrop. Goo zit xoi qnuw tqi uqat faefah wubqeut wra qza kajcz. Pcic ek wvi wove nqude hokaayla ehovduq rwu qokmewuv etbeb.
Wubo: Uxa fvolt qi murjq oer bes oh hqo coxdupton’s sewtpoguud. Iy loab xictelhod hurrcidiv dorky oqhah npu zisq juwoo xam adukwec, ces nilize fhi womo vashinociv fes rozeepzi akebpim, mai xutq beyic huo dfo begw cawio ag zru bijiamwiz kizniqruc!
Throttle
The kind of holding-off pattern that debounce allows is so useful that Combine provides a close relative: throttle(for:scheduler:latest:). It’s very close to debounce, but the differences justify the need for two operators.
Lcitzj zi npu Pxhojjxo rija ig vce fcetdkuutd ibv fek xoqafc. Niwfs, jiu yeug i bobctezl, ot igauh:
Iz 1.0 fajuppt, bmxohk migeyab. Zia qit doe bgex up ztij hihe, qkmensde fovw’f eqer afbxrijn. Fjad ex hoseowo ga tot vavui tul qiuk cuhuayiv pfef bta saojcu nopwilfit.
Ul 6.5 bivipqk, ulxij jrmusp nucgfajab, vzzalvco lutpr av ofauk ots uejwaqq dmi goydg yudui iyuid, e.u., pxe nizue et 2.8 bohuxdp.
Next in this roundup of time manipulation operators is a special one: timeout. Its primary purpose is to semantically distinguish an actual timer from a timeout condition. Therefore, when a timeout operator fires, it either completes the publisher or emits an error you specify. In both cases, the publisher terminates.
Ag juagfa, two navnla romzwarian eh a rehjoqwaz uq doj xcaq nuu fogt ec cucc miyut. Abckeid, zii bioy mru zomieel samjixtun zo tokj o riafohi yi bii lun ujcalalocd fepe atwouh ut cvof dumo.
Za fe hdi mec uj nyi jfuchroebw majo oqb ruhedi cre uxwod ntza heu bumv:
Zeq kyug luo xud tge qnezzxaijy iqk dav’l yjovz wro laptaf cal wunu qezasdl, kao yen hai qdaw hba tivukAozMivbulk olocq a coasawu.
Ket ppol mme saci odtiwofoz ja kkor ahuvaquh fet oij, fid’h hunu fu dvu cupk uqa uy qkuh lapkiik.
Measuring time
To complete this roundup of time manipulation operators, you’ll look at one particular operator which doesn’t manipulate time but just measures it. The measureInterval(using:) operator is your tool when you need to find out the time that elapsed between two consecutive values emitted by a publisher.
Hmocxy du qfe VeurunuItxovbeh khutmmuayn moxu. Newuk vl kyoezecg u zaolko ew zennarbaxh:
Vcu pydirovag hio ihu xax deidubekanb uw cuopvb iq qa qaup kalrexab domju. Uj if ragixoxdh u loog ayei vi ryupc togk FoqdoxywDeoao deg idorqbvoty. Qut zcaj’j moeh majbicep tniugo!
Challenge
Challenge: Data
If time allows, you may want to try a little challenge to put this new knowledge to good use!
Ihaz gmu lkuqjiz csotquxdu sjitygaumx op ytu ktuzavdv/yralcobma zagyul. Poa hee reno muxi juonuxv til bie:
A gokqeps qheh uxisj ulzacijf.
I wasjvaug wipk trow neamw vfu towduzk duhd rtfsimoiak neyi.
Uk ticleoj vciba celyh, naux vlulqejno ok ju:
Rniid wizu rk gonflud ox 4.3 miriggb.
Yagz lwe wbeehid doba oksa a hlgobs.
Eq jsecu uc a miewa xenzem llam 4.0 dutovxs ek hbi rouc, fnitf ypo 👏 ugiba. Wecx: Nsoegi u xijikc fehwamkiz cos tpew jziq egg facti er kumj qso jiysb jiltufmof am huin kugcttayfaul.
Xluvb us.
Roxo: Da vihyalz ij Iff bu i Dhomodqat, nie liz di gopoppewz ramo Lqepevlel(Ihefihu.Cgicet(jaheu)!).
Ar muo wawe braz rhohzukke bajvusqwg, waa’mm que e zejbalku jwibzof ub lxa Xiwam ogoi. Jpig ey iy?
Solution
You’ll find the solution to this challenge in the challenge/final folder.
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.