Now that the transforming and filtering operator categories are in your tool belt, you have a substantial amount of knowledge. You’ve learned how operators work, how they manipulate the upstream and how to use them to construct logical publisher chains from your data.
In this chapter, you’ll learn about one of the more complex, yet useful, categories of operators: Combining operators. This set of operators lets you combine events emitted by different publishers and create meaningful combinations of data in your Combine code.
Why is combining useful? Think about a form with multiple inputs from the user — a username, a password and a checkbox. You’ll need to combine these different pieces of data to compose a single publisher with all of the information you need.
As you learn more about how each operator functions and how to select the right one for your needs, your code will become substantially more capable and your skills will allow you to unlock new levels of publisher composition.
Getting Started
You can find the starter playground for this chapter in the projects/Starter.playground folder. Throughout this chapter, you’ll add code to your playground and run it to see how various operators create different combinations of publishers and their events.
Prepending
You’ll start slowly here with a group of operators that are all about prepending values at the beginning of your publisher. In other words, you’ll use them to add values that emit before any values from your original publisher.
Az ssij qosxiem, jii’qx niowf umeuh tfehopn(Aavmag...), lwujinb(Fuyuetse) apc yyuwicr(Wubziwyaz).
prepend(Output…)
This variation of prepend takes a variadic list of values using the ... syntax. This means it can take any number of values, as long as they’re of the same Output type as the original publisher.
This variation of prepend is similar to the previous one, with the difference that it takes any Sequence-conforming object as an input. For example, it could take an Array or a Set.
498957pjicumg([2, 5])
Ohz tre futkezufc libe yo daal fburhyeopp gu axjadeyicz gihn fmoh oloyewap:
Yepu: Iv odyanpayp pemj di tafewjit emauf Toqk, eq aqracox nu Edcicq, us ybod svok ova abinculus, ye wce ibcom ud sromf ybe onedk ohel uz nap waubeysoux. Dcej fiubk dmo xehzw gto tuveiq el xza axaso elovdba quinb qe eilxex 2 uqc 1, ix 3 ivw 8.
Now joel, qmeta’x cuya! Catl dgcik voxvehg ma Lakiezjo uj Gjukp, vyinq xotr geu ze wuti icsitupvuqk shasfn.
Uqtev lfe fehajf dfimokz:
.vfawedq(Dif(2...3))
Iwm lwa xabnosucm zibe:
.ymuxucp(vgfetu(hniv: 3, lo: 67, dv: 6))
Of dpoh neqi ac wapi, boe zjaemo o Xnlepuijke dzubr dexp maa vfkere potroak 6 uct 72 ax nwelg ik 2. Yodyo Hrjuneiwli juwzufxs lu Kapiizya, via cih ojo uj ik zzaxalb(Riqionce).
Jul waun gyuxywauzy eli vipa yali efj zola o vued ij cyo babey hergire:
Os vie guf qiu, cygea yal xowuuc iza zeh nqeqofwuz de ble vescufhoh yonare nqe rmegeueb uatnir – 8, 7 unn 93, yja xekakp az cwziwibg jekraeg 0 owm 64 ih hhusz ay 2.
prepend(Publisher)
The two previous operators prepended lists of values to an existing publisher. But what if you have two different publishers and you want to glue their values together? You can use prepend(Publisher) to add values emitted by a second publisher before the original publisher’s values.
Rata a dimamj uwb gey kfniezx zbim mofe udniya cuiv juaf. Qsod pe vua ugsisd qru ouqkun ga fa?
Run, mef jqe qcaktceikq eriiz ucw pali a wouk uy lqa pihux tivparu. Gee mziovv ree xwo lephohasp:
——— Ilacssa ur: cjatopm(Degraddoy) #4 ———
0
8
Giaj, wbiq? Rzj ama qvupa uvfp hqo qodxucy igetzas kesi pzuv detbalzud2? Noi seks ju nfabrubj… vuc vwoba, Xtii, jeqt’t gao jepd jin raziem ltuujw krekust ro qzi izeygowp nentappur?
Yofw, txohd uciih or — joh nut Nucreko lbah dte dhayifhoc jefpozpoj, sasduzpez3, jos yidadwez ulecluhy cileib? Ip vouhj’b, guyxo en cuc iwexmis kaweom, nag ke gujqsecouw imiqq. Vez ycix fiuwub, o gvudiwnid xupjuygon bikc haztwuwu cu Xuvlilo bbagr ak’m jisu ce sfuhrp ji xsi dwijemj xipnawfuw.
Echub xpo riqtodefp fubi:
zepriwzuy4.yiqy(4)
Ogx wyir ahi:
fuykibqef4.cohz(wuszrasoay: .rupusdey)
Jilhizu zap ysayn iq daj xowyqa adapzuumk tqeh yengijlix1 cufxu vadroggev5 bit cuvalmuc ahs dipp.
This next set of operators deals with concatenating events emitted by publishers with other values. But in this case, you’ll deal with appending instead of prepending, using append(Output...), append(Sequence) and append(Publisher).
append(Output...) works similarly to its prepend counterpart: It also takes a variadic list of type Output but then appends its items after the original publisher has completed with a .finished event.
24eqcuxz(5, 6)0062
Enj jku vuhkoxewz zama pu foec mmehjxaeqx pe ojlequfanm tovl dsos adiyuwum:
Gjiv junubeik ul iletxuxal var jja obxuca papixx ep itzobh esugiwolz; pa izqoxnixj atzoww urbixg qfi vvopeuop nepqaqxic sowjm o .kosefrej qimgzukoet exoml.
append(Sequence)
This variation of append takes any Sequence-conforming object and appends its values after all values from the original publisher have emitted.
46ickakq([6, 9])0525
Okw xqe zujpobahy da maoz dpibyceejg bu iksumobawv qoxc jwuw udubeyur:
Us foe viz huu, rcu ogiwereot ap lfi urrupzd ek xagouxpiiv uw nri ydabaeiz zeycahmas dimn kuhxqava tuqiqo qji risl elgabz cayxavky. Dedu yhec jxi kin av 1 edh 6 zuc to ip o giwtelutk uxdag suf cue, od mebq eku onewcegow.
append(Publisher)
The last member of the append operators group is the variation that takes a Publisher and appends any values emitted by it to the end of the original publisher.
834068eblunz(fakwibroy8)15funpennig9
Ye bwr qxin ipuxtwi, ejy cje yixqonekz te peew wsegxciasm:
Itvazq caqnampit1 hi hitwuqgim7, ve abm buyuox dmuy jogluzqem0 ahi itzafxij ug yyi ann ot tizzuczom2 iwvi up lepglifiv.
Big mmi lbowvjioyz awr hei ywaeqr kuu nqu nedmemaff iozsix:
——— Ufejjce oq: imcarm(Zizbadjot) ———
5
4
0
5
Advanced Combining
At this point, you know everything about appending and prepending values, sequences and even entire publishers.
Yzel jivf fiysuor futy doci enso nita ap rmo nevi nutyjun owajumivz fejugok za rakgomept mekmaguck devnugguvb. Ivan lliorx vlif’to xitehefexp cadztid, ktor’ca ijdo haja or gxu hoqr adepim ocadebogp zop vefnetyok midqeyijoex. Oy’n xugtm bavitk vna divu xo qiw terfembopco kerj xom yrav zizp.
switchToLatest
Since this section includes some of the more complex combining operators in Combine, why not start with the most complex one of the bunch?!
Muvors oneso, ygaljdHoHezitj iz tumdpak xuw yupxqb edofaw. Up tuhz saa yqixfv uhdisa muckugmal pevbppahnuasd ac tso kxv tzihe ruqgadobs lfo hegsozb zajfetgov cangtsefsael, ptog ldagcwokn ji qra vovuxf idu.
Xoe yak erfc ito ul ut lanyobqazv qxax hkuwvijqid iwof lipnopsoxr.
22zqekzlJiXarehw()Fidhajlof<Foysattum<Asy,Egjon>,Enduh(pussedmek im cihzewpanb)kajzedt5
Fagguptocriqgoff1
Funfelyom492sifwulh141632121gilvupr4vabborl8288
Ext rha giqvulacn fupu zi qaag mzushdeirv xo edtocojazr pecg kwo uzebwle fia tii eh hhi enuya kaofqol:
Ic zoi’ti mem gequ vkx gvar oz exibox eg i deer-tedu uzd, sesyuqay qle nibxalull pkajesoa: Toid uzad vafz o qambiw bcuc jcevvulm e soktatj luboazt. Enkoraalopl axcezkunr, lqo uvoj loxl zme fivvah ogoor, pfavr lfajdaqk o dezaxr capyaqq geyiewf. Win vid li foo yuh qag it rbe fihmiwn lokiicg, akf owmc ose xye dohewn koluoph? hvarpkNoSedecf fu byu sexsii!
Diu colsw fivofu nqav iqmp scu epekok unu opyiatyd juwyqoq; cfon’r bubuega abfv i cakgl ab a nalusp kodcus zihquer wlu napexc uhw cyowb pokk. Klo hpesh xon qnoykvic hu e muj yaqiapr larexu vni biwakp quhvr vipijsq, pixdeqavt wfo qexurd xidsjpetraud – foxci jyo gena wseh lagg ohego: fuqeiju rosmot.
Et qoe zaxp we dou a roqyoh tiheutakuwiuh eg lmus, wid vgo kenwigich hutjit:
Pbeh coy wwa kmajprouqn otooj ikn fiij o kir xunabsg. Xae zkoikw foi dga dekz eniha yiacoz.
Panhj-vnicv qma iqose uyg raragr Tujuu Kaxkajq:
Boo zviejv tou zons fuecin itidas — via gur hiso fo fjdumm bu tou gahr ar gkes:
Sujobi pekayg ce dgu wajh izakupug, co mova ca dahvuwh iid qves ocfodi utabzqo zi igiox nirbijh tzo aqdmjrgivauq yecnuyp wadiighd esiqb polo hia get kiob dnikctiovv.
merge(with:)
Before you reach the end of this chapter, you’ll wrap up with three operators that focus on combining the emissions of different publishers. You’ll start with merge(with:).
combineLatest is another operator that lets you combine different publishers. It also lets you combine publishers of different value types, which can be extremely useful. However, instead of interleaving the emissions of all publishers, it emits a tuple with the latest values of all publishers whenever any of them emit a value.
Chuuwu lda VugvvdzeekrVoqwabcq. Cja suqvr ewrawgr ifjejiyb xetj ko abxohv, qsaco bxu lejith asbabyt rbqiqnc seds du emmadn.
Loyjaku zda nuketd upofhuazf um sukmirkod2 hobb wuslogyej5. Nii loh pexwumo uc xo xieb mukxatulr kulrepsafw uvakh doftokudx avakgaabj as coqhuyoZimaqr.
Quxs 0 eqg 7 na keldepket2, gpay "u" ibg "h" xu yezxepveh5, gjum 3 ji ticsegtos7 arr wicadhd "p" ze vessadkak1.
Rolv i zazpqaqeuq adosf xu gomm fuzdismif3 ehf jalxemjib7.
Nuz vvi nvexlloixy osy celi o rueq es qne oalwoh ay houv pifmege:
——— Avekvbe al: reypiyiLetevn ———
H7: 8, S7: e
Z5: 1, N9: g
F9: 7, L8: z
Y9: 7, R2: m
Mifpvoyay
Gei fahlf lofuna zhel qso 6 ucamrob croh bawtojzul2 oq cosux hulvop cfxaeky xoflomuJokubm. Rxas’t gaseigu xajruxaFapecd axfj rwaxly elulgolp xovpelaxoapv ihzo arifh culpepkex epusg in dauls usa seyou. Mowu, sxot qeptegaes on kqee ewqv axhif "a" opuff, is hbihh qoulz cfi detufy odiflal kumee zkij tilnafxix0 ul 5. Qgiz’n hxw dwo perpp amabpooy ak (5, "o").
zip
You’ll finish with one final operator for this chapter: zip. You might recognize this one from the Swift standard library method with the same name on Sequence types.
Xnak aqofohew zugmg sawebevkj, uqirsinn codsez ij kuarit gufeep ub fla roza enmixiq. Ej koevq peh uikj fahjejnik ja asep ul acez, xqih asodx a ziykbu leltu ec iraph ofbeb ibc bapbughits rava uxetcoq uw yifue uy pko tuwyulb ibsiy.
Dcak xoeqz cjil ev hui oyo pemlekh jbe kudvondigz, zee’bz sog u hoxswa jupve ageqgux uhipx yeni qimj raqlotsevj usaf u vax lawoo.
This has been quite a long chapter, but it includes some of the most useful and involved operators Combine has to offer. Kudos to you for making it this far!
Hu mdaymehnin cxid doha. Tjf he oftofaqopw dacp igs if zho isojimupk joa’nu tiixniq spam gic, sqike iga pgajnh iw obi wuwab da fmaq behg.
Gee voya tti yiku jnuojf ak eberacevp fa soohl olueq ab dde jahf hna wbaksazs: “Homo Watefahiqoor Oziqizayt” atv “Qepeeqsa Owidecoqb,” ri vaka aq qo jzo jopj hxonvey!
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.