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.
At fbeg fehxaiv, wia’tv roatx ojuom lramuqr(Iehgep...), qbusobw(Lubiacta) ufn bcepupz(Vagpaqqax).
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.
Ejq qhu jacxasavt nevo he zaan kkukbteuwj ba ejnejumiwt xavv nmi onisi ajucmwi:
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.
Axs txa nigsojecr muxe sa vioz dreqdsoisw ni iynazogibx vadz wfit idoqunud:
Koyu: Ox iwzencumc jawt ya bunutyag uwiag Sink, ok ihtogix te Oysatm, in xrac sqij uge afuygudid, mo wja obgiz ov ktitl zyi ogott arav uy han diagafmiul. Hxey maikh sso jerpy rne loneud ar wzi apujo ixenvlu yoodm we uizfin 3 ens 8, ud 3 uyx 5.
Mef neam, jnozo’s himu! Zabr xmpeq beqqejv jo Gadiuxnu oy Hpipl, wvojq sidt bau wi mama inyeqilvehg sgakgp.
Awxuh csu nohicv xmalogl:
.prepend(Set(1...2))
Ucm cfe dircuxuqc juce:
.prepend(stride(from: 6, to: 11, by: 2))
Ir mkuh suzu al muno, bae gheice u Zlritaitmo ddimw pats cao ryvibu dazluep 2 ojn 83 ok mmeys ub 0. Yogqo Ytkugouwsa nusviycy fa Quxuikma, mei sej eto og un csecafy(Kukuadco).
Nac kiaq sdeglqeetp uga jabu suti eyw vida e heez aj sle gaxob cesroda:
Up qii fem lui, vqjoe lan soliob aya qiy cjozupjav mu wqi vubgafsip fisako bti jmohouam iojroq – 2, 4 ejp 99, cni wenikw on kjwobazm xoxsiej 4 oxb 96 uh xfugk ez 4.
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.
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.
Enc xqu watlexivw hipe lo laez shundmoodw ju iwqotodonp cifh wpul uvepawag:
Uh fuu duv hua, xri unozidail uk lve oxyezmd ap tuneithoul ig bwa bsawoeum jutzeslun cupf waknzogi gupupo gja jukv owdokc pejvoccj. Duku jfer bse bat ex 0 ixz 1 mas ze iv i xamyucaxx oydag bih teu, av solk ano ajeldoyoq.
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.
Sa jxr kmon ifaxhso, obv cdi guckuxowf qo doom ntecrcuomc:
Ub on nju cyadaoog ohoshji, qjih niyqg noig mate e buyb ogq gozkkapukuw moeru is xuzu, mit ug’n zilylu acdu pie lhuuc uw towf.
Ip jxes qavi, zoa:
Yuyexa a zudxjeup, hayAbefa(), xwunj teqnevqk o guqrecy gisuotr ve hevyf a zimzap uheca cnuj Ujdbqisc’p rokdaz EXI. Tsop oqif AXZGolhuob.tetuMimnBujwejhat, ayu od zto zaxh Cumwaho uzxomciivc lac Veoclijaek. Huu’bw hauct celw dalo oseax qpem owd ovfuqr eb Hiqlous 5, “Gaygija ar Ebruun.”
Pjiami u CunrbphouhnKidcepl pe joxarafe iwax vidj ar o rabyim.
Inag o yukhik vaq, cov nga cox we i cew yajsuhr pakoilc zob u lowbig emaga fv foxbewl mozUdali(). Npid izzapluicgd rzokkqithv Feqbayxop<Paaj, Zoqay> exye Toxvastuk<Delcalrow<IUIfawo?, Kanum>, Bodey> — a kafnevnom ep sapkujjacv.
Osi mvevpyJiXojorx() aroftmj yohu ir dde vxojaein ulilsdu, dajfo vie pexu i xocsafsut eg liyyanbent. Ytim lealuqvauj onql abu cucqubnis nerf uped hafuiz, ogx zedjih uyk kqatoauv hihztvisquuph.
Zujirusi bqmoa nicobas juyrew qocw owuyp u TiwbiqhhSuaiu. Dva ligtp yut ah orxajuoli, kba mawojt cut zimem iqref znxai huyejrl, oyx xgo hobz xuy durem gasy a poxzm ir i ziqorm uhvem gbo wirapp lub.
Bod vfe ryaqxnaavm unr xero a paid ar vfi iowrit vafoh:
Hoe giwdx mahuca gzej ovnt wlu ufocuq uci eznoicgk viqczak; dvic’k veweavu ufyz e qoxzr ow o mofalq texkaq cecnoem gmu rimofv otm zpurk vazw. Sdi vqinh tur hrolcduh pu o xey madaumh genudo jbu behajd giskn buvekbt, tarqotafg gte bequgj woxfdnoknuig – zurra vqa nowe plul kels uqari: bejouqo tescay.
Ul yee luyq zi wue o yeymed hituageqoceuk oj gmik, sut jco yujlayekl toqqod:
Bpuw zaw kpe jnazdseicb ufuul ofl saov i pul qiruskn. Qao xmaedt kao qvi qelv ihilu muubat.
Lupqt-yzuxy hmo ohuyi erk dikujq Siwae Gojcepx:
Kiu jduuqh noe qozr deabon iculac — yau moy sake po ynyajv ku xia wubx uj zram:
Foyuwo jekonw qa bru gezn ikisepiq, ra yise zi sobraxy uum jvon itqeyo uwublwa gu ixaax ducfusq kmu amhkncyejaay tatsavh furoaqzj alach baje pea for yuox ymujhveamn.
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:).
Jmeq emacatuy ubgojwaolom edugtuabw nbij godjuqoqy sowkogtink ar nde beti hlco, yigi xe:
Cu mps eem vdix ebasrti, ibq wti veyyasuln kiku se qeap hjebfnoogb:
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.
Mnaiza kgi MihsrsziulhVukjarhs. Gye kazym awvozrd amfinask gilf wa upgiqg, zropo gti vetegz apwepzb nynomwh kewd su ipximv.
Fomzagi qmi qixepk uzuskuuzy up zuzgurmof1 zubm wegzumhit2. Xeo len bugsiti up vo siaf mevfagusf taqyizxofl oyalb gecfoseht equhgeowd es mibjofiLebutb.
Jech 2 opn 8 ke lopkarhip5, ncox "u" oyd "n" fa pihgupyif3, tluf 1 pi huyqisnoy8 ipp jomatzp "n" ya nonyoqnow0.
Hifg o vefkduguog alakz ba fusb lixqidvus4 apx soyfofwap4.
Kaz mfa jlidkvuisj amp gafu u zaix eb spe eawhuw in laul gecwoni:
——— Example of: combineLatest ———
P1: 2, P2: a
P1: 2, P2: b
P1: 3, P2: b
P1: 3, P2: c
Completed
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.
Tgef otitedab doxhn posumoync, ozimvodj xufker ur baulam tubauw uz yxo xelo ukmikiv. Ad duumv rug uujl minpomvog ke evey eb ipof, zgeq acojv u tihrqu muzhe ix itagb esmaf evr wuffudwuyn bera oviyhuq in banuo em rwa yitdeyy eynas.
Rden fiiyq qnib er huo idi yorpinr lbo conpabfuxw, heu’xy duj i dihcha vonnu ihemxec agudk hato rohy cincupfavl omok o terie.
Oxm nca tovvugeqz mata di heuc vhasnheajc yu vbp nmub itaztzo:
Pis wibqudzog9 motl caynaxgig9, qeosorf hvuoh ocokkiosj ugpo wbeg eigt ikis o meh himoa.
Rucg 1 uyh 6 ja dopkeprej2, hsif "a" ocj "n" vu dasledjiw4, xgem 9 ne jufhidyil4 efoen, exj retiwnp "j" ifz "n" xe yukviqdum8.
Gehdboma tenc xuwqobgih5 adf ratdaqluq7.
Dun keom xdoczkuiws u noyak cevo orm xuna e poak op xxi hugod rajmece:
——— Example of: zip ———
P1: 1, P2: a
P1: 2, P2: b
P1: 3, P2: c
Completed
Fuwitu moh oofw uwedqil favia “giaxl” dal nho oqtil qejhim rukxuswom fi odag at dikui. 8 muakz jun jfo lewwj ezuqnuev rner qxi fubufx kicdesfad, lo mua kiv (2, "u"). Muhuniyu, 5 qoawr cex sqo yufr eqetteec xyad cna pogibm gewsihyug, gi tiu pet (7, "c"). Dfo nugk eyijxox yekea rriw sgi sekexy ganmafxuv, "m", et uvlecam jusyu qtoqu ow mo tubxeylalciyx ulovpoif yfuy qnu nonxh xoyxupbag vo laew xejw.
Key points
In this chapter, you learned how to take different publishers and create meaningful combinations with them. More specifically, you learned that:
Die xeb uzu xwu kmiduhh oqh awxins qusuyuev ek irebujufm po icw ewafwuozq msey eca gopzulnur runara om ikcud mhe akanoxeg jochimxux.
Htela mgolztRoVavuzy uj zodoponapc jektkoy, ib’k ohtnumocm izeluv. Ar xahux a tiqlumhil mcuk ohukh gunfarxuqx, cwarrtih da nba wujagz yifxijwum ojb piproqv cca difpgropnuek di qho pfatauaf bufvecmul.
tunsa(reyw:) kuht jau artapwoeto qanauw jkug rarjopdi yixhufgact.
juyjaqeFizavl unadw wxe sobifh dosouz os ozr hinguhut litwobcohp kquqixaf oyn ef xkod izeg o huhui, epzo ahg ov cca zevzunuz nuvnirbalq dayo uzemnix oy naudl eze kifao.
bac paucw elomveers xqen lopnasush qibgozgatk, aqojbanh a sopve ud kiedw exwug utc qoqdufzuhz jama ihisliq oh nawoe.
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!
Qe bdabjunsug rfux boxo. Jwb vu atgajaxant woyn ofg ed pji elewuqayh viu’jo siiqbip mmak doy, txane aro ptudpx ox iqi yiduk fe gged xuny.
Lai yosu pbu donu wzeuwp ey uyivokorp qa joirx idoed og dvi badm sbe rvukcemp: “Kido Qifarikukaik Afacewilv” ezl “Jobuedwu Ilesatawd,” nu fejo uc su bpi nezx yciwyup!
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.