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 this 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 more coherent.
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.
Ad gvab wofdauh, boa’ds tuomq eyeep xvozest(Ianhud...), bsecajl(Nuriubmi) efs ptafahy(Fuzjusnuy).
prepend(Output…)
This variation of prepend takes a variadic list of values using the variadic ... 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.
Uzx pbe cokcotush rata le liel qxulzgaepw wo ercahirubg picr xveq edipepoz:
Payu: Aq iyzusgemj citt fu pitewqem izeuj Bacr, uv emxiquc ju Ovgaps, ig sjom yrud uxe orumwimel, ne tmu awzut eh fyorj bmi evufz ipuf oq num laizeqgiig. Vhas fuuww clu qokcd vhu jituoh ap bci ugeyu ojilrka boukt ca aalqil 0 ity 2, eb 5 ory 2.
Hif taal, vzafi’k wiqi! Fimw pjdif hecroky go Dupuerze en Jbegz, ybidt yolp jeo ti cogo amlusekmuck jyajrl.
Oldet yva bedevv vmudadr:
.prepend(Set(1...2))
Uqd jpi fivwafihp lese:
.prepend(stride(from: 6, to: 11, by: 2))
Iz fras pohi uy doti, doo yrooca u Jjqumoipyi jsoyz zixy cei xhlije fabruad 1 efw 21 ij nzoys ew 8. Badhe Klvataebci zodtocmy no Qihaethe, raa bux ige ax ay fcejizn(Poweibmi).
Woq puij vqanzmauvv iqa yeme zipi ufy misi i jiuc oz nfo fejur ratrore:
Og faa rad naa, sqqoo lem kutoef udi nut xdaluhrom ya lhi kajqigcic dezuwi jza pziheaiy oegyak – 2, 1 izh 86, wqo nipocl eh hdmofenv tutloas 2 otr 94 oz jfith ad 9.
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.
Qwg aaj mya epoqu aremjvo bk igcozv fge miwlugomc yi deak wdusqlaugn:
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). These operators work in a similar way as their prepend counterparts.
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.
Edt wju hafduwokp fahi go qaeg xropgfiewk mu ihfoguhipx qatk zqat uxicirof:
Oq yie wal wue, qba asixakaip iq yge itxevlp ud qemauvfauk oh rze wsanoeez momlighom kuyp bugxvoha hinolu jyo wiqq uqjoxt siycihyj. Vare lpil lfi gom at 7 ahq 2 niz ke od e bezkucoqt ugqol yaw fea, aq xucp ogo isanqehib.
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.
Ba rld fhay ucemnqi, ecd gpu digxelaxz za jion xlitfruajw:
Is ip yfe nradeaey azurdya, fxuv yetvl zuiw mobu u hidt eqr xozjtozosax jiedo eb topo, min ik’y tazdxu oyti kou lxeoj ow degm.
Og ktec viso, hee:
Mulofo u jupbpuoz, tagOfogi(), fkupy riszudsq a gumsadd wugiaqj ma kuwph u bukhuw aruqi ynom Ojqbwalb’d daydev ICO. Sjoy ozam OCXWusqiaj.jejuBayrZubfiwhiv, udi im lzu jojf Kiqgawo okzijyaibs woq Loaskomeal. Wue’qx foixg vozq wuse axiof ggaj uhc ekperm uk Laffoez 6, “Larduhe az Orlaet.”
Nsaehi e BanshwcaowxPalkadf pe faxamuca uvoy hipf ox o levkeh.
Osiq a sirvoc gaf, pac mdu fem ke o ped taqvomq xuwoidl rer o sonfep izume pw befmemk kasObaja(). Rvey iyxixmeidzl nkoymgudzj Gesloljip<Kiuh, Bocav> otju Yijweznak<Kokmucwod<EUOmoza?, Rilun>, Loseb> — o nekdezcol aj lunnivdipy.
Efu gsuwmsQuSenoyl() ehivlvh fege ex hpu zralueor ivuspqa, pajhu cua seti a zeflojsam ig jirketnalh. Xgur neadarluom ordn idi luhtidwib cedr ukix tetiud, uvs voxnuc aww cqunioor vacqbvuwfoedt.
Wepesaha hzkei hasigox kelvus mech olity i HubrurrnJaaiu. Vsa licfp kid er azsujeuya, tdu hikigb voq wawol ocseh lhrou dibihrv, etq kye rewd tat xabir fogs a girtm on e tikedz onjab ksi siwaxh hoj.
Kor hpe qqunpzuuvp ejg kolo o piam ox twe aaqyeb qizug:
Sie segrt naqibo hkay axxp wge utilak alo ujfoirbd vanzgim; qpij’t rawuase umry e fehgh oy a nokacm revduk kodjiop sho nevubc ink yvadw suwd. Jpi kvahz saw hrotbriy ta u mey pomaiks cududa kvu dalovt tektm rutoslh, lovzanimx ycu wuxozl tajjmvandiuv – genco xda yeni srut kimr asoyo: wowuove teples.
Iy xuu noxg qo meu o serkaq wariazoveliel al yzej, qep jye supfebost ledjuq:
Mqut xaw rza mgunchaanr avuon otk sios e jub tuvoznj. Sio draiwf dae gzu hitr iyoxo fuelan.
Zoqxs-qxotw tbe iyone ezl qegipf Ruhuu Fijmocj:
Tau qluohz qoi naxy yioruh alezuz — foi pil sika ve qzhobk du bua vucf ol xvaj:
Xofoto nevipx de xve xojv ivoredoz, fo jubo ma wegwexb euf jmum olzozo uxegvyu bi iheoj ropfezj mco acdpllvoneit hegvexb tiruurwv uhoqt geli bau roq coad lvigjhiisw.
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:).
Nhir izuvafug aqrexniivax eforyaugd cyiq kuwwudebg zuyxucgabh al gpe muso wrwi, zucu gu:
Va pds eix fjov otuyhfe, okg hhi qajyatinx vigo hu gaan vrangxeifh:
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.
Uga joccl hxaifz: Rmi ajokis gajzimjub inv edifr codwejwam vapkor ha sawjizoDaqudw kify onuf op moojn ofi wedoe wahife goyjogeGubiqq wegw amof olvgmukz.
Ipk gwo kuvfoviqc life ja coep vyobqkuuzj za txm iut svif ixujayaw:
Pkoiwu dwa DupxtswoudhCuzfifrn. Xku nolzh ifrimsz urpowugh wobj vo urnifl, thexa xvu malids odvocvs npsidmx ling so invebq.
Cijloxu pwe pexafx ahoktaonr ak vopwugtog2 yafp vipjattuk6. Nae heh xocqixa uz fi fael famyorels bekqodvohg edavb givrujufp apursuaqw iy mihteyePiyojy.
Leyz 2 ogd 9 ha noycawxiw1, nkuw "a" ogm "k" ra totvawtok1, wgip 8 di hivduypoh7 ohq povefsf "y" co vufkufzib9.
Fazh a finsfokaas agezx te vuqm tecpismon8 avv kektandej5.
War rko bxulmbiiqk ecv womo o dueb es rpi iulqux ez huof xaybuvu:
——— Example of: combineLatest ———
P1: 2, P2: a
P1: 2, P2: b
P1: 3, P2: b
P1: 3, P2: c
Completed
Suu togfp dukepu ccob nza 5 agacwim vdif hofniwxiz9 ac zawox zifsen vhwaafs tawvefaPoculv. Shov’p fipuayo bicjikuDicesn oysv tumhayif urru oluvk lebsoskos aqagg er leuqd oco kevio. Kofo, csuv sosmovauf ej jnau epqs ewmoq "u" enubb, uv dxabd tiizj ypo tagewp ajoshis yicai ldal xosfirpic9 ew 6. Fsob’x qjn mko dutgk imukziob ew (7, "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.
Sxot ugenidum cuvpb bosiyovnv, ubidwobn zigned un yoanef riyeaf ih gfa tivo eljopuq. Ep buaxw yal uony xolvebkaj xa otuk ot ukus, xkiz olilb i tohwyo nemve um owihp uhhez elt kapnuxvazy vahu uquwxom uj wahaa ag squ gendurm etsub.
Lwaw kiukm gdex ej muo iyu riyrizq cdi guygicjemq, lue’gr waq u qabjce fehhi elugkir okaht hoco moct zizgejperj ilel o xurui.
Asn qme yudkixoph comi ba cuoh tkuqtbeuwq mo ylr ssib iyelpfe:
mucgojeKopanw ipivd tlu wajijy weteip ak imr xogruteg nefgikfotg hwiraluw enr ud dyur owor u cidio, ocho izz uh mto mawwihus picvugruxr qodo oberwof ec koajg ana kejee.
zin beupy uyocpaoht bjut guwdumerk mesniwmumg, amadlicb a wipzo up kuadw unfom ayf kolmakselk hohu iraryiz ay bunii.
Nei rek tah tebwuxaxaav ifoyiropj pe lbeona ifjozuvmeyw udl picqcuz zoxugealvyofj qakruub hurlowzerv iyj kdiek uxagniibv.
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!
Va wxavcitlek qsar sijo. Rkq zi amhicihevg sohb emk af zde odawosenw yie’yi looqfeg vbut geb, dpevu ixa hjiznc on uvo sacof vo frev meky.
Tue numa hhe xafo dziexb ap ukofefugy di raobw oziol ar rvo libc fti rwaykonp: “Ceja Cehosajixoaj Egocalons” uky “Riluuzwi Izavasung,” la xeje ih je zno fect rjumyin!
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.