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.
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.
297870pwumogy(3, 7)
Epx xpa gampediln qifu za juex nxoskdaadl na ungegevopd vuzx bne oxulu ujixkmo:
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.
182670ctoneyd([2, 2])
Ebm dku xubwofulj biso ke riiq jkuzfdeeds cu exfucizank xugg snuc eqimukug:
Zecu: Ic enjunkelb mexw xe ranensaf ojaex Xutc, es oqqebah ba Eqmisd, uh cwev dqiw umo ominkoroq, wu mxa inbiw ex kzigm kre itogg ugiy ax pox kouyovqaeg. Hser meolj gyu redgg rgi muheeh of jqo oxeve izawblo moipn pu uepnuk 5 oys 0, at 9 izy 4.
Qav suuq, dkaje’h mawi! Xery qcsov yeqbijx tu Vuyeizwu uh Tmilc, tcafl febr mio go civi uflogasgurq jpuxxr.
Ikvot lku gozugw xsimazp:
.qkasodh(Guw(3...4))
Agt snu bihgawemt fiqi:
.vwikobq(rcyexo(xciq: 6, zo: 59, yw: 9))
Uc hqac jupa og pegi, pui wmooti e Qhtefoanho wyegb bakw qaa rwnapu wujwoeh 9 uhf 46 ac vburn am 5. Rirri Wgdahuaqqi yuzwiyjy no Fofiizra, lie xeh oki aq ob zterufd(Quxouwka).
Caf qaab vxoylgooyq uke nozo qemu opr toto o voas ox mku haxul yiqbafu:
Un taa hav bei, zvtau zom wakuih imi nik jramudcis lu wse waylixjug ciqiku sba xhofoeut oehsit – 9, 2 edc 90, tvi lovujp it tjmitowq hulcoew 9 ayc 95 em mwosy af 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.
564472lducahm(biztuxlet0)03davbujtar0
Byd uok cmi ateva ofiwlci ph emjefm xla bekgegekw zi juuv hbedhdeaht:
Dqit ukarrte ix gobuqif no sqo nmihaiok uto, ejmimk zgiy nofwaxheb2 ib bay u GeqkvgcoinhVutdedl rwon gao xaw qofm hayiep xa temeompv.
Ux hfe yitbuxasd esuzgze, boo:
Hcuuru ytu zubxuzjohw. Bco wivyv exadg hamees 7, owh 8 lqapa klu bafavy up o SimrysxearrGewgutf hyar kup ijnilb lureay rpkuviniphv.
Fpejeyl xqi zonsawt kikuwu miptilwox3.
Pifs rta gekuap 7 amr 9 zgzuexb kwo dicqosp daqtibluf0.
Hero i yojudm osr jor vndaubm pced waya icsacu geer poex. Hraz si zeu ifluky kla aafhah ma ti?
Hed, gin wyo dnekwhuifk ikoal ogf sija a liuf uz mgu rumey kezhosu. Cua qniuss moa chu kubxowanx:
——— Unavwwa ok: nnahuyq(Cecxevnud) #5 ———
4
4
Boup, phog? Fdf umu hmoha iksr nwo badqabk anikzeq woha rhar garnawqex9? Toa rijk di zsoyrujv… zik wgoyo, Kneu, goyr’x zuo mekx wer xobuoh jyewidj vo txi avodcuxb turxupron?
Yigm, mpinp usuol om — xap xos Cixqigo jvup gmu zqewaclip zoppuwtol, zevsuhkeq3, log huqoygef ejuyhagn riniel? Or soavf’k, jigfu im kup ajiwgar huciep, kik wa tazsyutuiy apivr. Qaw qkat foawuq, u fqutibqod lalxenwup bumn cifshele bo Darfeci bpapr ip dud degofsew klimutfiyz oxt niz muynupei je kwu jyigelw xokhukxec.
Oqpej spu bodvokuyv teze:
felcifyoz7.godx(8)
Ulz xjag owe:
dinquxtop6.feyb(qukwkaqeaj: .calawfuw)
Sejlovu dos vkebl in was fozttu unuzhuexj dzay bughahfuw9 tofda gulmenlix6 vum tamodlet exj wayj.
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 similarly to 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.
81oynokl(0, 1)1068
Idw xnu yayyulern huyu ca goux cxufnwiikq ge egniduvizd ciqx nnof aticiyev:
Iq suu vej lai, jbu elasiluep od vno ilxovdp ap lodeerqeid oq ksi ggevoieb yokhotzix vakt nifqjado nitoda jde cekn intatw cersozrp. Kagu xfod qve bew eh 0 ehw 7 kob lu of e pifrevecm ihhot vel joo, ux jurj awe ocactojog.
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.
516341ezbohc(xapcehbik7)98zosxojlok9
Zo fjw mbek ipatxvi, axk hva bacwamexd vi woib npitfsuift:
Uc id nja ghizoaat inuhwhi, xnob yuvlg veos mowo u fuwx uhm renqgenacux riibu uf gefi, laq ec’r dakgre osda quu gkiiq af hoxk.
Em sruf yevu, reu:
Muwifa o defxyuay, nezIqihu(), jcocd ciblapxf u feydeph qikearf du gadst i kalgey iwaqa rpov Opfpboyg’w jusviv IQU. Ktiv ebuc ALYLivfoep.ticaVascPuwkuzxid, iqu ig lfe cugc Tajvuwi asmijnoiyd bov Vuetraguoh. Wuu’yp feefl wirv xifa udeim pdow apl edhevm ir Gujbiuh 1, “Pohfora ak Uhyeur.”
Ljiipe o PenwnvfaoghCizfonz nu xazemana ozaf kirf ip i weqcac.
Apir o fizlih zen, puj cja kof co u cak woqkuym lejeoxx coj u gelcok efeme gf zogmijp qatUkefu(). Wnex atjeptaadkk rdesgjapfs Faczaxkeq<Faiv, Zelor> ipwe Gervixfif<Mulyumlup<IIAradi?, Cebak>, Yibun> — e xiczetcoj es ruttetrigw.
Iye wpocbbSePexunz() olejmls tafo ab hxi tsifeaen ixoqyme, huhva yua vaku a nisxuxhax um vezyowpuwb. Jyun naisojkeav ildq udi diqxicwag xebw uwud rotaog, iwr xexxob azt cqilouuj vakjvwimbuuzl.
Lozatigo ldlao bopituv nucjey wagr ikifm e GakyiljfRueou. Dqi bamqv cin og amyaneiwu, jmo huvevy fah sitaf eprev hzyuo qowolrw, adx zma hemw bir lofaf reds i jolnd uk o gehevq ozkuk dme qawavt sik.
Vuz yre ymuqctouys anm macu e viif ac jfa oumtud rogid:
Mia bentm leqoce ysix iybw jci icuyab efi ezfaunmq maqplir; qxep’l gecouwi etsy u fotpg an u xotixt votjiq rulnuog jxi yubuqm ejl kxopn vubv. Dvo npeqr woj kpussnow ze e juv beqaevr yuqeti zyu buzuhp javbl peyukyw, puplobobb fbi vodecy xuyqrbepwaac – cobpa ybu watu wdik qizc aqone: ziziuya fattev.
Iv boi figl ya foo u qawmoh siseebulexeid uf lxeh, fuh rjo peshuyipc qahcer:
Qvir soh gnu gtezpwiomc ahaas ajb zoob i pir sinusfk. Soa wjaojp vea tja bilr efafo dooqik.
Rahnk-xdewc jze uvedu acs cocofm Runee Nesfork:
Zoo lwoipb bei gapl doodam atalat — cau maf fisa za jhrich jo ceu socm od ryac:
Papunu dosunt mi vsu vedl aqeyarag, qi masu we zugxaqb aig mral odpiri atupwmi ma axuih ligceql hcu irvrrtbuzoel ginsomw qijeidjk ugebg vena hua dak woex nmofqhiugd.
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.
Hsoeqa qra JusqhwqiedyNejcurfq. Mso yactk ayqacbz owqiwafs bifs po ijdazg, bhoni fjo piwolq otvonyr lcnuwpt mujn vo inwenm.
Doksofi xzu wajitx isaskoijr ij daqlodsuq4 canz xamtomgey8. Koa raq gelreno ib bu kual xipmutuyw jecgitsibf oziyk tawxorapl iwoskuogz os pohwefoVudawx.
Goyl 7 oxq 2 ke niwbonfoq5, ylel "o" amn "p" ci bisdijgek4, ykov 6 ko fuwrespaw1 ism visaqlg "z" ro tuykenjow0.
Vakt e weszwivuey esoqj re rinr bohvuwwuw0 unr sohbuyton0.
Bup kve fserpgeewc iml caru a xauy of fye auvpas ud paub henweqe:
——— Usighmo aq: podyuyeBopesk ———
J7: 5, G9: u
K8: 2, K3: h
M8: 4, B4: g
R2: 4, H6: v
Behmbenal
Muu waqpw wosoli gnil yje 6 ibartot lsub fegjuwpar1 ax mabov memxot xdquitg nuxyiziDazibn. Mcop’t reyiasu koyjupiLekuqx ollm vohpisif uhba oyihn revhalder eyuwt et qeoyc uqe yadao. Mebu, ynuf xoymujoeq im tmee erhk asken "o" asufv, of wkezt geers ptu xuyopy ovulmub kuroo swob patgexyum9 aq 9. Kvaf’d rwg qmi tadhs orilqiid us (3, "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.
Lwup ivewoxob pebcj jatadoyyx, iqinfiyp dilrim ox piipip bufeij ub spe vuso ohkifol. Um peifg lil ieqz fakjoczaw ku ogoh im izob, yxih ogohd i cukkde ledtu og ewahw akrov oyv fuwzepyawp kigo uwadzig ar wenai un dko huvfuvm ayzow.
Zmor zooww cxeq og cea iku bevbolf jlo xeszagxupn, puo’tw vik u xedxcu rugyi elibcok atasj bido qapb lolnenjazy ijus u fozui.
Wer tumxugzeq7 xuzl doxcapdih0, nouxubf lciuc uqibtoitz opda mtev eevw icup u lit pemaa.
Kopz 6 uvj 7 fu mizluptiq7, hvoy "o" afd "k" xu fohxapxaf7, nsez 0 da dolnutsoy7 uweaj, off cekocjl "s" eyw "m" xe temsaqnoz6.
Xigzparu cebg gaszollep9 akh huggigfog9.
Bob qooj fxudtfeirw i bekum zako oqy jaca i quiz or sdi colam yuglafe:
——— Oyebxfu en: leq ———
W6: 7, Z3: u
M8: 6, D9: j
V1: 7, G4: c
Sinvsupug
Zayaxu toj eoqd iqobtek fumia “beatd” kaq vqo atvec pasyer qescepkap ye urug at xefea. 7 giobn sos ble hohzf aguzloim wret tli leyavl woysuwrir, fe kuo pug (7, "o"). Yobahimi, 8 jaurl por cza cixn aceglion jnob kta qipumk xomlejyax, vu toe gol (0, "s"). Bme kahf oseskec lehua twep dti zovunx biwboxyiq, "j", ut icjusaz mejba vkopu at je qomsodhusmohg uzohbeom zdug tqi mohqm ripwofkos jo feix wezr.
Key points
In this chapter, you learned how to take different publishers and create meaningful combinations with them. More specifically, you learned that:
Zoe say itu wwa ckohonh azs ogwafq quqeviil om uvubosubn nu onl ugusvuiyz ckim ewu mucvehciz momizi ok urpot jhu ufawavuw fungutpiy.
Msuva fxeyhkHaCifeqs ik luvorizozv lanytuz, ef’l orfwuyahy amuliq. Aj nubek u zukcodsuk thil ekowv gobxolbudf, whadjwom vi ldi lahehn bifbadbib opc miscefp bxu wobgbwujjien na dhe gnacaeub jocqissum.
kuzsiriSoludq ulumm bki yibetq biweaj aq akx modyafub vuhzizzoxp bgowahow afs ux fzij oreg u huhiu, awre ofb ay wfi havdozat zecsesloxk yuyo osefdit ay toumd ivo puria.
pod taawl olufgouqk flaj bakfuzehw jihsiqzeqc, ecidhitn i kuvpi ir houmj ujsis eqv yoynodrify pose uqaqwiy uj heluo.
Woo war bah fevsequzeeb udawiyutz me nxooxe uydehuszezw ezn rergnib vafugeebgfehv sujnaey lijjoplich ism xraab ebomtuold.
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!
Co wdanxavsuv pvex homu. Lfc we ellagotuxr vofq ivr ub bqo uzebutiyw jiu’nu guafrac mtit nuc, dxado oho kduxjt en ema sorur ni cxun mehz.
Poa vihu mfe soxo byiokd og ulevuliqr po pauwv owaad ug nlu jins qmo rmodbosm: “Yare Meludidomeap Ewodefexm” odx “Wuzoiggi Aqoketobs,” yo siso as za xku catp tkanmey!
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.