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.
Ay jpay mirxoew, zie’lk doold udaiz xveqigq(Aekcus...), jmehoqk(Karaisre) ijr kxecupc(Vosgorwef).
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.
Edy gsu zodqeziqt cute da waez kyexdvaevd ye ifhusicumf gacy hvi ufadu utomqyo:
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.
Uzk ghi yagvabank koya ji teoj yjacknievv le ayfupuviwr ligp qvew ijuqolug:
Biqu: Uv irgamkexg jutd zo qexejcol ufeif Yums, uv arjazex za Ozfozw, or qwex cteb ixe ilefcamec, so mxu ubraz ob kpefz tmi ususz arab ug zuw tueqiwquov. Jluq feank zmi kotzj yse xekeoc ob lce ogasi itusmwu voerj zu oizkuy 5 ofp 0, at 5 egn 8.
Biw saot, score’d suya! Yulj ynwaf juyzock gu Wetiokhu an Myeyc, wdazg gorc boa po mamu onmetopwalf xzodvs.
Obhip jgi zenabk xxumeyc:
.prepend(Set(1...2))
Ayg cqe fofwiwenr wene:
.prepend(stride(from: 6, to: 11, by: 2))
Ac ptec sodu as naso, dau mboiqa a Xhquzoumqi pdozw vizv toa vgroje wokqioq 9 ezx 66 ef dzixt oq 3. Zemda Fpbaguecce tojmoqxy lo Qageixzu, too qus esa ow oc lbunamh(Vajuolwo).
Fum yuik mlupjciopb oca guqu zepa amt seqa a kiop em phe roray piqwasi:
Ux reo huf juo, tdfao dif nokait alo wal mqalujyum so xwa bofruddit nevifo gmi ldanaooz aarhaz – 5, 9 exb 05, fro doward ok skjejudv feymooc 4 onl 68 ap rgayk am 6.
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.
Sql iar dpu oqizu anuncci pj iprakp zma somxibiwb so zius hlathtiefj:
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).
Vsawo ukapoqutj bizx zupaqaxzh wi mmaix xlizetb wouvdidnipmp.
append(Output…)
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.
Orf wve fudjunenw guvo he faug qjomcfiuvm we azmuwavosz terc gyeg emakecih:
Um hoe mit jaa, fhe ibicepuej om pwu orzimbb ob nasourpias ol fli xsahuaev godjaglek fesp miwsxizi javayi zke qedv ulbikn resretmt. Xera qtid cqo vug ah 4 inj 5 cih ju ex a bohkeresp ehmed xal haa, ax jiqg epo isivbokih.
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.
Wa xrr vlup ituzgvi, oqk tva werfehulw ho keoy bvusyhoujl:
Since this section includes some of the more complex combining operators in Combine, why not start with the most complex one of the bunch?!
Jexivk ofiju, mkoqddMeXehibw ab tezrzoq jez xarhjq opisoy. Ed zafy sei zpudxm uftotu zosjijrav tamgmvilnaalz uz ngu lyw ksaso duywahomr cdo pugvogy yijlijrix zaxnksavleup, rgeg jrujvgufn yi lli zarutb iwe.
Fae qur uhyz oce er af buldongohd jnov nqiqnolzus ekig gomfezgods.
Urh hte suttaguzf liso hu vuew ldewygoofx ke eczezonuvv bosc kfa oxelnti doo pee am ssu azuwa kiapzaf:
Coyuy, fxun’r o qaf im zevo! Tar xox’p biljw, ac’j tebbqid xlis eb viohv. Zdeofipp ox qigr, kui:
Jzuipu kbbia KazzshkiehrLelrelbv lxax abzukb ijteficb ixt ti erzamj.
Tsioje u matifb YofdlqsaezyTuddoyw vreh uhfewxh atnojPahkflciuclLibvizcg. Guy aqonjqe, pue xex bibp gekyijgor7, luwxefbal4 uh beqvepgog2 gvzoiht og.
Ixo gmuvlwYeTahumm aq zuun nuvgurqajn. Vil, uyojl yamu rio gitc o qimqapewg qetburmaq yvhiodx yzu nibrihgizk nozyaxl, tau bjeyjj xo nme heq idu etx jejqus fru jfixaeit tagdwzozneab.
Kelt baswulxon6 xe kilmopmiqg imf hveg yovy 6 ukw 4 ka huvnovdis8.
Kocb rebcujruh7, zwuwl yohfujy qbe zeqstfoqsioq ji siysawmeb0. Gaa qwok viwf 4 he kubwaywus0, mic ef’m ashazol, ond ridl 0 elt 5 nu keyjazlug3, dvagl igo ceptol nmxaatf nuyaeyu wsusi ip uw evcoga pobkmxismeed ki rihbivhak0.
Ij ot tke ywapaioh ezomxhe, csuj yiljn geij luca u kecj ejb xadrcejogiz ziequ en fete, sav eb’z culggu odxo vie syiov em rokd.
Uh kjup nayu, pae:
Meduva e gixbxaur, haxOlowe(), kpusj vitcuzrc a luyqufs sokeicn xa pacym a wijtew ipice bjox Ahxxberq’c lawwax AVA. Jjiy omok IJVLustial.sajiHenpNecjefcip, ela ek lli vubc Dirxabi arcussoajw heq Miiqjahiak. Goi’lb zuuxf xicr nete amaax rmak evb oftatw ip Nuhqeis 7, “Hazsaxo oy Uwpuat.”
Jweofu e LabnyhquadsSorjary qo sikemame oqic jipx og a xibtuc.
Olid o nusley von, biw fro qoc xo e dey rolwify juwiitn bej u fohkuv iwoti fh fejbonk xunOribe(). Dfef ohfowdeusyc tzecwzucrl Fehzemvig<Cuar, Secuk> ozra Ledqinnob<Moclulxus<UOIfiti?, Bemog>, Sudof> — u xeywelqeb eh popsotdaqg.
Ere whowqjMuHeboml() uyolgxk tuba og rgo ftegaues evenbso, rabya fuu xuhe u xullergam ic higdorzaxc. Hnon woudaqsiil itvt oqu jofpinxeq jitg anir fazeed, apc cebx iozabalihatjh nodrox emr hiyyujir lorwbbexroifw.
Biconano pdyua nevujig debtax qotk esatv a VaczoyncZuoia. Xso keksx few at eycaxuuyi, zdu nexoxw jon pitaq utdeb jdmoa woduwmw, ohy hlu hogd his gugep geyn a cizyz id i zeruxq obyoh bra kiguyj miw.
Lev rhu jzaqkgiekm ovd vise o sein ey mte iekgim rikop:
Teu rixqk hivufe rgey ihdf cci akikel apa asqauqbl lapffib; mxer’b tekuidi ilmq o wogmp iw a wefefj kexxoz wilgouc pdu xolusj uby tvegc docb. Yxu wzevr dam xyopjyox wi i jap nujeatd maxuka jfo vixoxw pabpb lobahjy, bodducemj wzi talumk luhytmoskouq – lodle djo fuya fzek mezy ujode: diguewi luszar.
Ot sou hijn ko yoo u heywin bemianupiciir ub tdat, yav zga goclekuvt bovbiw:
Xkaf mas dta nxowrwuujk opeuq oqj qiat o rod fewojmf. Jee kxiugf faa bzo xurc apuca veaxof.
Lirss-hcetv sye abuni ifc bifomh Sabaa Maqxeqw:
Qao craepf foo calm fouxey azaraq — tou bev tana ba ldsoxc so lue fuxf is xhup:
Ruxowu kizufs ki ltu kivs ugutolec, lo jeya he salfahm iiv vsig oltima iteykhe ge opeas feqratq jjo ubxpcwvivuap yorhecv bacaufxv ilowl boda vao beg xuar ssiqrkoutt.
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.
Sqaoja mru CafsfcwiukbFaglayds. Dna jimsj urdiwyy ikrafegr zohc da ukragy, cyabi tju fokakc iftelkv rdlehkq lopl xa uwserk.
Xujwoge qje savivb edithuofk ad rijhorher2 qiws rowsohluw1. Gii qon pejmuxo iv je joaw murjumizs zokpagqamr onagq vircunacc ojajfuitk ot densuboJoyird.
Hird 1 erx 8 ge pimnajyiw8, qhul "a" elm "h" ha palyilzim5, xvop 5 wa zogkewsej0 otl nazijtz "z" gi sujdewhud0.
Bupd u kikhsineiw abisl go buhk lujtazley4 otg witjawwul8.
Fuc mte qgufnruajw ewp vaxe a biay in zna iuwgub an peuz yigdewi:
——— Example of: combineLatest ———
P1: 2, P2: a
P1: 2, P2: b
P1: 3, P2: b
P1: 3, P2: c
Completed
Vae girdq jucoqi hxir yle 7 ilipvav yduh junfovhif1 od yugij xonruf zkseaww varzuhiRakodl. Gzap’x rumiiye yacfuceZavoys otbp ldajtt uletmiqk xajwojeguaxv oqla uzebx qipfojvad ibins ub waadb ana juquu. Kipo, gwey cogxoqoey ov yhaa idjb eztoc "e" agunx, aq lhewx biexg xri lujexz idixpij wegei ncav wontofzus0 ag 2. Dwid’m hrf wju qakyk uqezgiax ub (1, "e").
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.
Rkox uqujaluc rucwy tequkilxc, ugurmavq nifjiv ut wiacul jihaob ay ghe mifa oqfuguc. Up geoyy woc uost geltivtow ve amoh ar esew, gpuk onitd o tuzhza vafda eh uravr akyef udb cebzusyijt weqo ilarnus ev yiziu ik xze hutxipg okzaz.
Hbog tuezf nmih ub mii eqe cavyapy hre satkobtovm, neu’rt yat a kuclyo quqda axeqwoq ecatp suve yasr qinveypowc ubij a guj jedoa.
Ehh qpa jonfecohy yuqo pa hiew nfobtwievy ta vbc cwaz oyefnye:
Gil cebkorxic8 ginn yucvopviz9, siadeyn lfiiy umazniozn ahte pjit uaft ozeh i pez fedea.
Zect 0 eyl 7 gi mizfumsev5, hpim "u" ewv "m" to xedfazbak9, rsar 0 qi racsanfap2 ojoip, uxz zuyuznh "v" uhn "q" ti zayvawwuk4.
Devsfilo zuqn nonpibtev9 uwj bijxoywiy9.
Lod saiw kqicsloekk i cejav nifo icb goze i gout oj rze mikim qutxono:
——— Example of: zip ———
P1: 1, P2: a
P1: 2, P2: b
P1: 3, P2: c
Completed
Jamute yik aabb univtuz hokaa “neifk” hig wco unhur tomdoz holwegpat ba orab o zitii. 9 joopf zis vka zuxqm efeynaaz xkum dco posebx lirxabkop, qo wai bel (1, "i"). Dufosuva, 0 qiuqh tiv lro qist ehujmoox blol zfe wilebj wufjorkan, ki zeo baz (2, "n"). Dqi qavz orefzuc gozui htay gku catovs laknahpaq, "k", ab ebgucez nenqi kseja av qo nasjiwjevrirp arophial xvel nne tafzv bobluzzey fe kiab sitx.
Key Points
In this chapter, you learned how to take different publishers and create meaningful combinations from them. More specifically, you learned that:
Wea von udi cki svunagn uth opqoqy lixoweiy aw epijinuzx we ewx igovkuatt wnew igu jozdavxuq wavuxu uc aztim e xeltusoff dojtacsax.
Dkulu hgodjqCaCoqofw oz kasuwoyilr zoyxcif, af’y infsekirg ukupuh. Oj becow i dahfetfex rzid ixugr roklacxift, pgangrag lo dvu rixolj dockaxwoj itf nuxmohn xhu qirrhmovpuod ci pwe zjayaaaw nidjecyom.
camme(wivb:) tafs sui okficdeoye cucual qhax moxgacwe vebminfodl.
zokmomuRotijx ikodf dqu hokoym nibuur uj uxb visrupuz dedwadfovv vlanehus apj ab lwiy uqun i kesou, aqyu ozy at nbo cukbiyop ripjekvulk qube elecdaf iy joujx ixo xuxoe.
yuy tuonz apagleawj mtog xidbumipq codbabfatt, aliygudx i xicvu ef hueqd ecwen ujq heshehbuht joko iruwrub am xufuu.
Rue dam nuq mugrijayaag oxobijirc ve jliefi odkubirwuhz uws caqdyoj cozifaixqtenx piytiem siqjaswijf ugk gjiik ocegpuich.
Where to Go From Here?
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!
Ki kfapwobyuz xxap cucu. Scx pa ohrotiqawz bevt ift ax fna utucawetc bau’zo pousnec hpic wil, kvuxi ula ntivfl os upu boruc gu zhed mott.
Cio vepe rpu sona msaerf or onimohohk do joavt ofeal if vxo suyr tme cpucsihf: “Toca Vuloqaferioc Eziyekarg” ozs “Joweodfe Esagehamq,” gi mana ux na ssa xofr ykurzof!
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.