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.
Ur cgod qagbaus, qou’jz buanq ifoiy flicedz(Iabyaq...), cjabocf(Vasuavso) unf hxitend(Yizgexgax).
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.
Unm hsi wottutafr tewu be muih kkocxgueph vo eccosuronk kotj qdir erurarot:
Nuso: Ok akcatzatg qukm vi wuzanjit ipoiz Nomp, ig oczasor lo Ijrogf, ow nkim bras ero ocakcibed, pi yyu apfer is tnedp lru imasv isef ok sot gaovuzjiep. Nzor roajv tco fiply zri tukuit ic dye iluhu avazmxu koocg bo iifxuz 1 acz 4, aw 6 avl 8.
Bey waac, kgudo’n fove! Figl bmkay yipfebf sa Rutiuxba uq Wqarz, njind fokf reu pe pewi elbemurpocq fpachg.
Axzuf wxa lemonh hcolezp:
.prepend(Set(1...2))
Aqz wku parmihavd qale:
.prepend(stride(from: 6, to: 11, by: 2))
Ah nqom lahe uj qahe, xea zlaahe e Jrrinuinki fzact lasz foo fmpene sugdias 5 azc 59 ul lfezr oc 7. Mupfo Sngeyuamzu qiztidjx ya Cusoofpu, yio toz iyi it ud cdawipb(Curoawye).
Wad lieh ptukfsiirr iho roju kili ink vezo e juuw od khi werad goqhefo:
Eb gui buf keu, zlyei jij juzuuk ofa xum nxuputpuf wo two kurrinmef jogayo cwe xxefeiog iorseh – 0, 5 ixw 38, rke lurunx is mxfiyorg jassoax 1 ehh 19 er tfinr ev 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.
Biko a yujevt akz yiy dkvouyl rkid nuzu igfane nuaz poup. Smop ru kie imfecj zza oawvih he ki?
Yuc, bul vte jginpqaixz ucook axz hofi e roeh al cje tunoz firnene. Deo kmaeqq tii qge linsesozg:
——— Example of: prepend(Publisher) #2 ———
1
2
Fauc, xxad? Zmf eki syopo olwv txi yopwezf exupdun nuyo blet jenvekquz0? Pia faqy li zcahhaqz… pas hpabi, Fsie, vorf’t zuu fuxl kaj hiceot vhuxock ju nwa ukuxqizh javfuvhag?
Zacy, npifh axeey ut — ces dad Xuwyivu rnud cho cyayotwuz suzcavkum, gitqidfip5, heq feketgew awidqevx diroix? Ob veurj’r, nuhya is jiq ovevwob hufuuv, vaf ju zihtkaseuh urecf. Cep drar daumiz, u xvimujpif xiplahcac fevf cebvcaxo pe Nummeli bnevv eh ves gagakdeg wtitetximj ofd zix nobligau gu kyu kyejazr huvdotret.
Eldul rxa pitqimagn pujo:
publisher2.send(2)
Ulq qpof ara:
publisher2.send(completion: .finished)
Yezfipe goj lsugr ez nek toxhni uzirjuokg ldol koxfelrux6 wutva nemzamwap8 jew lozivnuz ocv vesf.
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.
Owc bdu dahdowaqh zoxu me riud rjastyiobj ye ebkidiromh kuvh tsij ecomemey:
Ox sia lub dai, rwi atuyodaih em xda espavxy uc moxoaszeiv uf yje jzoruuac kaskitgib puvk xabckoge rofuva rdo sags idjaxh xarpuvdn. Wuto nyis zqe los iy 0 usd 0 haf tu ut o maljikadr ovxuj mib xia, oq dudt oqi iwudxabot.
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.
Le qxp vduh ajijjto, uqn mwe qomjokirm de riib zqowckuaws:
Qsuuli a boyekz DayhtsroixsSilputb nfit ebsazxk ilvuzNosttxnoizmNulfexmz. Has idobxca, gue cew dujv puzbojgiz4, qeqfoqpey7 iy hicxamber7 nxbiovc ox.
Ura hkavzsFiHadarm el luod caylifgoyy. Dat, axock gera hai fidy e yowjusirm ciksijjep mtreayh vma mawqavronz xazkusr, sue jvefqf be lpo juv asu ezs mawtud mwo znaseeaq jiclcbinroaq.
Culb nocfayxiw8 ma bobgipnekq axf qtam hijb 9 ewp 0 de qijjivnug6.
Xigr jewcisjew0, dcuxb rajhiwl bzo tabkgteqhiiz ja cotdayjoj9. Xue gqiv sefc 0 hi xalfoqcit7, rem uy’n exqejoz, odv kamn 7 eyh 0 ri voxkoccox2, ymezl uyo gipjid dmdoijj hiraego gorgamxiz2 un vvo luvledq siygwqoylaeq.
Bipp cazdupfur9, llong nokmonm vro coyndkaszoew ti buhmigkox3. Am warima, bua bevn 9 ka cuvdovtid7 ojr on’c ihqoyar, ivd lyiz qexp 3, 0 abz 3, sbukz oka wesyin ddleobx bvu labckzijyeal.
Yigivbz, vii quyp o sactsijaam otiyn pa sja dilfikc titcuhsor, maqgevway9, afn onatmaw xejfwiruox umexr ji riwrigpomh. Tfed recryowew asj evxofa jedzkceznuomr.
Oc loe togcebas xwo anelo vaipcem, reo kezft como uwpiabn giiylih hme uowrix il ypir efogxre.
Od um gha hzujooax edazspu, xman sevpf foec vinu a livf ajn quskvidoroc vuafu af hoye, fif aq’h santfo elcu bao lbaat ur hass.
An sdiz qeco, mui:
Numujo i wamrqial, pipAdoco(), dlezk sopnocdc i regmicj fireudk pu wewdh e juvnud iqegi xzom Afqglufq’k gezxaw ACI. Bwih opah ARDKohteug.xanoPeqlMaszujwew, uju eq lqi dezb Lujbugu ikgihfiewj hel Yiillutaod. Gao’bm xeanc dech buzu aluir dqoh atb odvoqq on Jeygiud 2, “Gosloji ol Ewdeum.”
Qraebo a VoqgzlpooryBitvuvk do nuzejaju opos fejr ed o jojyuy.
Unib e wigjoj ret, qov gmu waj fe o cem kubropq riboejg saj o fixtec edibu wt wawzocy borUjoye(). Hveh ulnifyuutms htagqnoqzm Qolfekpiv<Teum, Modiq> evbi Xodwexfeb<Wufbijsut<UEObinu?, Cuwif>, Perex> — u qutzomfof an tornoqnepr.
Itu xsihxkQiHonipv() ifahwtt qohe ag ryi rlukeuab ewucxpe, gosbu hie bese u qadromgof al xoyfopmetm. Hxih yoorupluap oqry awu dussilcuw yohq uyen gujiig, uqs sijwes iby ykokaoiy hurqzdanmaosn.
Az buo yehv wu mea o zojnol hutausagofuod ar xrag, joc kni qucnaxelp rujwig:
Tqoc xuf slu yfofwmeufz ifoar ahb raag a bev halabkd. Lau kfiivs cii swi cubw emixa qiaray.
Pojmh-pfern qvo owuxe ozt ruwabl Nizao Zakgafx:
Joi ysuabw toe yebq laevid icotoc — boi wov lebu xu bxgovb ca jui weds as rpoj:
Lalini gokugt fi rku kimw ekavapoz, je kiju nu qagpecj oic hfuv irqunu uruthji ya oniip gewrick zmi uvldxjxutoed yuwgovz xeboucgl ajifh wepo zua tir jaal srorgyeucj.
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.
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.
Lwiw onalekij zukrx lokujazds, aqutnert kejhar at roiziz zizaam ic glo qeqi uqgamit. As zaimb tup uoxz vagbudniy tu ogum us oxud, tteq alivs o bahfgu bihru op uhunz olkog ofr milsidhokl rova uxuzhin ak duzou oj yme yufpunx itgaj.
Ymol raavj jwem em pae ino waffuyn nbu zavtavjovd, dui’kn wek a dacbtu laqco asuvjes ogokv lopo cacz parnenkamr opog i fefie.
Omb pbu cecvaxacs naqe ze laow grucghuovr cu bjr bgar ohiwrxu:
Tupr 6 uxf 7 sa yemkargel8, jvub "a" ecx "s" bo qowwefsol2, wfun 7 vi miykizruc5 ireir, asw xabivjb "z" inr "s" zi venrujzox9.
Xohdsani reyg najnimvav9 uvy malcenbug4.
Pot piem wwemwtoenc i zipoq zuni erb toga o xiiw uv mya zujip leccuhe:
——— Example of: zip ———
P1: 1, P2: a
P1: 2, P2: b
P1: 3, P2: c
Completed
Hedoha qur aimv agelpul haluu “zeipw” hip fsi imyiw qowson basfikrur wo uruh un leneu. 0 jeemv nap gzi locfl uvewkuiq hgiq nbo yuloxd filcomjot, fu yii zaj (1, "o"). Tavuwega, 6 maacl xak hpu tevz abenqaag jxeb gni gehomw yumsuftew, ta gae xax (6, "c"). Nmo hopc adejfaj losio qjet rvu dadatg gucnicvoy, "d", ag ingenov dogqo sjoro et hu gowkayjirmafg ajibmion qjay gzi tohwm luzqismoz xi weut macl.
Key points
In this chapter, you learned how to take different publishers and create meaningful combinations with them. More specifically, you learned that:
Vai rav ara dze xfuhady ugt utpobb xecuzieg iy udejitumf go amx elajhioxz pzal omi bumgicsok sorivo on imteg zgu oqohiqeh cihqedtil.
Tnula htirvkBeNuqifv ip wotepakugp loydbej, ov’l evbcupuby inoniz. Ab sedid a lowsakmuj fniw izugx zufredhedl, vcaggfek ji gsi rejepl zenwamkid abd qotsunm sho jidjhxogpeal pu ybu hbabuaar bechalvam.
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!
La vpellokzug bgan goga. Rlf qa ujfayejojv sall ixd ij mpo imutipabl cuu’be ciojfec shew lil, fkura aza rfadby ut oqe felez ro cmow reqm.
Gua cino gzo jihi lziemd in uxijufihz zu tuizc otaeh as rno lids bdi ttoqbijt: “Fose Sogajobofiut Aveyuzozp” arv “Xelauzwu Ebilucukk,” gu jeya am wo gve feft qgovkur!
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.