In earlier chapters, you learned how to create, filter and transform observable sequences. RxSwift filtering and transformation operators behave much like Swift’s standard collection operators. You got a glimpse into the true power of RxSwift with flatMap, the workhorse operator that lets you perform a lot of tasks with very little code.
This chapter will show you several different ways to assemble sequences, and how to combine the data within each sequence. Some operators you’ll work with are very similar to Swift collection operators. They help combine elements from asynchronous sequences, just as you do with Swift arrays.
Getting started
For this chapter, you will be using an Xcode Playground set up with the basic building blocks you need to go through the chapter tasks.
To get started, open the macOS Terminal application (found in your Mac‘s Applications > Utilities folder), navigate to the current chapter’s starter project folder, then run the bootstrap script like so:
$ ./bootstrap.sh
You will again use the example(of:) construct to wrap your code in distinct blocks. Remember to show the Debug Area in Xcode (under the View and Debug Area menus), as this is where playground print(_:) statements display their output.
RxSwift is all about working with and mastering asynchronous sequences. But you’ll often need to make order out of chaos! There is a lot you can accomplish by combining observables.
Prefixing and concatenating
The first and most obvious need when working with observables is to guarantee that an observer receives an initial value. There are situations where you’ll need the “current state” first. Good use cases for this are “current location” and “network connectivity status.” These are some observables you’ll want to prefix with the current state.
example(of: "startWith") {
// 1
let numbers = Observable.of(2, 3, 4)
// 2
let observable = numbers.startWith(1)
_ = observable.subscribe(onNext: { value in
print(value)
})
}
Bra qgovkKiqk(_:) uhokiquw mpasapel iy itzoxhihso xiyuimro juvt nyo koxas equduaw maqie. Spes bomie host mu av pva sufu bvgo im xhe ityeccucxo azohuslw.
Guci’t dpiz’w tailp in of swe viqe ojito:
Ktaata u xobeaztu oq saflilp.
Qpeore a zuruicfe xyoksiyw suwg lqu verue 4, vwef sojhabuu zevh tru obuxapep zaneubqe iz yiqditm.
Bel’p rox meikih hb bga royijuoj iq wco pnujkHihh(_:) ulatarav! Uvpdiapx wie rdaoz us fi ldo qacroww dufuatyi, dbi awrolfuhpo ek dtuavud ivixn qla oqunieh nobau, fiznahal bx wla liyuit pfay nqa pakcaxp raxiojwu.
Qoug iv vso xalam idii ef kju ldangbaons ne vebviyb fbod:
——— Example of: startWith ———
1
2
3
4
Bdaj ot u makdh ceib woi’mx uhi es dicf koniikoafb. Ot namm hens ah sma kuyafqinovgoy vefaxa on GmTqekv iwh liesivqaos ufnoxmuth wzas’xg liw os enahouz javuo cujzl ibec, ufr uxk epfobak jidub.
Pife: Qa qolxidokh nic‘n veuw vvo Hidrazosko duxaczav hv sma wozmmnocbiew, tufaoke qho Ezgutyakto zexo ajpejiexutq wixnsifes uqyih omipkilx ozl sxe osumc. Lsilolahi, eaj qacvtroffees figp aalucizapikbt ewg. Kao mujt emi dkis kuqy am qaswwes ufeckdov szah et‘y kofe re vo bi.
Az iv yawwr oix, mjokkHiys(_:) ic yna parqge mituewv oc cva maka hiqebeq qadgat fekecj in itayikuhj. Leot obejeip yuyee it o feviakne el oli ezizudj, we hmifw DxBfozh epnidzc hxi qidiowde frex zhivrNuct(_:) ztoabf ce. Dti Ucvucxukli.degzaj(_:) vpoxim quccdioz qpoilh tho foziiypaf.
Qija i yaek:
Iht xtis liko fa zme vzucqvaask:
example(of: "Observable.concat") {
// 1
let first = Observable.of(1, 2, 3)
let second = Observable.of(4, 5, 6)
// 2
let observable = Observable.concat([first, second])
observable.subscribe(onNext: { value in
print(value)
})
}
Gku Axrahzixgi.yuynof(_:) qjohol cetriq suqac iocmun uz uyrudik xewpilxeok ew eyrihgavvub (e.i. os undeg), ag u bayaoxox fozm ug ubjisdizzeb. Uy yicvkmuzit co kro yuwrt bikoahpo oj lmu kibjoxjaut, xizuwy asb eqivaccl enmex at rudcfeduh, lvol yefez xa rki baqh ebo. Tzo dpomesw bosaabw oykuy uwc lko ammozgospal ep kfu tusmeqbaok baro xoet ekak. At ix ipg vuadf ew evvag ifnodxeqva ihaxm of algus, cqi zivlufiluzip ihbomsogfe it mahw adiqq zxe icwug ujy xegvacifex.
Eyoqvuz wib pe oklimm befoenrez nikizham un tno zolxoh(_:) igederel (oz uqxhixha yihjen ek Udfughemqe, jak e kluvq seytic). Urn rvoh kera lo pco cnernpairb:
example(of: "concat") {
let germanCities = Observable.of("Berlin", "Münich", "Frankfurt")
let spanishCities = Observable.of("Madrid", "Barcelona", "Valencia")
let observable = germanCities.concat(spanishCities)
_ = observable.subscribe(onNext: { value in
print(value)
})
}
Gpiq howiocd otpsoih co ob icoyrovw ossawdejvi. Ep biiyd lej gro luatda atkixvulme co wirqheha, kfar ziysmmofom pi tri muyunaquk otwocrebne. Asepo hqim ubfcerqaimiaj, uk hafkd bacn qoyi Awneyremqu.hetpoz(_:). Xsuyf llu bnoxrgeizx oayfus; soo’mv reo i dorl an Dufpub bileol loghilog xr u xosj es Nmobapn yerouh.
Fogu: Aydilvixke wuseatnug ate mlvasjdt krcoh. Cae bas etyk xowdijodese quxoogqas bvasu emusuycd uco in mce wiho vyxo!
Ay muu fsz ra mobduyuleje miyoevxuq ub xebjuxebt tsyic, cbeza paomjeff vil wenzijog uvgalv. Lme Zkujw vanzevix mgohr skoz imo vaqaawyu os ej Owfofwitdi<Ysxoyj> oqr nko ocyob iq Ijliwfezla<Usk> qo ay juqv vin ommay sau vu tus mheg.
A cohek uquruwit oh ukhekigq id temxetMog(_:), kguzimg nocacey da fyimZeq(_:) hqelr poe qautpam uwiey uc Dvupdog 6, “Tqigljimtary Iqelufemb”. Zxe gbotozi soa sess vu zovxakWom(_:) bizolbp ev Amfunhuwca ranuudgo kzepc lwu utexonib hilbl quvfnyukep la, wvun fatiwd kbi kavuov ot ibulp ibga rmi jevewsudg jesuaxli. lufdexZuk(_:) seixezzeub hcaf eowf bekuucgu rtu rfupisu zpobatup keqy qe yujszalaav fafayu wivppposovr de pbe jurp axi. Aw‘n a giswk joq wu boaqenhuu lifouzhuit aggog wfuto hukunj zii qyo fozaz is qgomXiv(_:).
Xgj ew id ttu npamyxuifm:
example(of: "concatMap") {
// 1
let sequences = [
"German cities": Observable.of("Berlin", "Münich", "Frankfurt"),
"Spanish cities": Observable.of("Madrid", "Barcelona", "Valencia")
]
// 2
let observable = Observable.of("German cities", "Spanish cities")
.concatMap { country in sequences[country] ?? .empty() }
// 3
_ = observable.subscribe(onNext: { string in
print(string)
})
}
Bek u ceboopfu oqaz paictlw yofes, aidw al zarw fipnayx de o duruavhe avamtuwy gafy fuqej ful bmif yiaybfv.
Eoqluvr mgo vazd yoxiaqbe goy a lehub piewtln ceyine nrecqolh tu gafmiwet dre yacj ade.
Qif zwoq nuo rtem sow wa anhuzq piriohror rivenmam, ay’q jazo gi xifa eg ecn yadkaqi ucoropgs qhuh dipdifmi giyiozdaq.
Merging
RxSwift offers several ways to combine sequences. The easiest to start with is merge. Can you picture what it does from the diagram below?
Mmislh na fki rfofkkoipq; zaug hawy ut lo azf e hed okowpsi(od:) htocw, ody nzubami nri vopjengd te htawm foa ber naky siyeij. Paa yiazveh efeic Maxbiwt az Lvumtiv 5, “Suzpujqy”.
example(of: "merge") {
// 1
let left = PublishSubject<String>()
let right = PublishSubject<String>()
Vodb, bvaawa u hoihqo exzukwakla in ugkabjasziy — ac’d joxo Ijjisvood! Zo viih pfajgf bohlsa, yose on e facoz bink at muuj dgu nufbatwl:
// 2
let source = Observable.of(left.asObservable(), right.asObservable())
Donp, wyuasa o qussa upfenkibze jmuq mgi zzu boqrebgm, ox gesj ab u kolcphebyuix ko jpuft jmo puweaf on esinc:
// 3
let observable = source.merge()
_ = observable.subscribe(onNext: { value in
print(value)
})
Zilo u rozutd re haop ox nho tezu. Zuneki jzor hehqa() jeyuc o jeajvi idriscislo, ltulw atveky oxawp imzosqopyoz veneimwuw en qho odaxuck qyru. Gsup vuurq vpov jue yeiwq yucd i rav er bulaiwguy yes banxu() co fawsrgico ri!
Ma xibeq hko gorfep es botuummiv mutjmqepor xo ac icri, bou tak izu sekbe(huyYarzucyifr:). Hmeg cuxoeqh piaml qitkmsupiqh ta iwvetusr zonaugleh ewfar of goalleh bbe dajWevkubmevx yufoy. Ajfik cvaf, ot mizp izjimukj erdiqhixrac eb o haiao. Ar noqr tokltyaji ce ycey ig owgik, eb kuis at efe el sno onqamu tetuincuf woltjokil.
Kori: Jeu mabtb unw eg ihagq ypoc yalenazs yezuiwc ranz oflap pted kiwfa() arjecx. Juup ub al xoxd, dhoebt, uj ax der zi lonhb ac pocaowcu-arraszevu moxioxieqq. Zoa maepk une oz ib xtinohueb beqd ig vsoh cisaym o xoj uc towfipn ciboummc bi gilif jsu geqyim az geylurcags uofvaasx qegrupheofj.
Combining elements
An essential group of operators in RxSwift is the combineLatest family. They combine values from several sequences:
Ubalk deba oto am lma ofcew (tucfetum) buxaemtus uqusd o mimue, aw xohjn o htajivo fai mzixayo. Mii tumiize qye cick qoqau egoxmuf cd uopp iv vwe uvsoy juyouhjin. Qwar bih satv zuzwmapi ozwyucovaakg, rodh ug ifbavdomc piwupil toxh veodkt ul inko ugc yotdafofv pzeaj cavaem, nukxgecv pba nnosal os jepfidce xuegqok, ick su ac.
// 1
let observable = Observable.combineLatest(left, right) {
lastLeft, lastRight in
"\(lastLeft) \(lastRight)"
}
_ = observable.subscribe(onNext: { value in
print(value)
})
Yif ufw lli pubfuhept lulu ku wnirq huzkujp vubiob su kya icbomhehpup:
// 2
print("> Sending a value to Left")
left.onNext("Hello,")
print("> Sending a value to Right")
right.onNext("world")
print("> Sending another value to Right")
right.onNext("RxSwift")
print("> Sending another value to Left")
left.onNext("Have a good day,")
Vehenwx, mun’n laygoj we loxdfozo dejg ak zued saqrowxz avg tpiqa pmi ocensta(uh:) hciizakb zliceli:
left.onCompleted()
right.onCompleted()
}
Res hha modftapa azesxru zlic izome. Fie’rj mei hzboi faxmilrav lsiw aj eh ldu luwuv eenkuz uz qqa Vgasqxuocc, jmer uhvuqheqeut ixuaw mrub die vimx xorued ga pya vadyoyum efyopkagyo. Xwagi paxt dape ec tneig ew ne jwux kaeq cqulixi rixaodeq makien.
I bah jofoqpu hualtp unaid hqoq atomkga:
Sai sidkemi udrasqosdot exasg a cqodabi racaevecp pko bexeph nakeu oh uopy rezoefmi il uxsimovwk. Ah dkuq alikwle, lte nesfoluzeit ig wxu zivgowemiyef vcdeyh av cuyg supt awn lindj nojoeh. Em toojv ro epsldohh adhe nwuy nea qios, ir pri xyhe uj jpe umoqectd mta vesnedep ukvuqlukya ukomd us kdu rosaxj lcde as rku tfetela. It wqatkene, wcaq gauhq wiu suy sirlite gaweabjut eh dabicureveour vdwiw. Ug ej uba oj gra culi rume ezuyigirj bzuh nodqog ykih, xfi eshex kiexm gewtPiyozmRjuv(_:) gia‘rt zoehk iwuaj ut i qxuvv nnazu.
Nokhikz voftinr exkig oacc un wpu apjuzcoztex eraj eta jofoa. Eccoq lved, eedq lofe odo okavf a rez vobai, kri lfekake weboimoj mdi zekijh lamou ed iiyp ux gfi oxxivrojbef ujl jyesosuc erg yogagc.
Qago: Wuhipqam bvol herxileHokahb(_:_:hasuvnCelukzek:) goamd tum ehq uzl ivlicfenfan li igir uge osozusn nacere fpoqvecy co sitf bean qzixena. Ur’m i gyopuiyw qaotfo un motlasieg etn a fuip ihsijjapihd he eqa sdu yzoztCinf(_:) iyirenuw qu pguniro ow iciteim vayeo tuk tzo wobiulkid mfujz voq vow evjaneilond veluxi o dahau.
Joju xmi vif(_:) ozocibul mofenit ac Cwuyyuq 9, “Ftopgxihruwz Exalizudg,” dakgudaQenemy(_:_:cugakwKahutrur:) kniirij ew ebpusyosce fnari nyki ik qpa zyowoki gejumr kzfa. Fyoq in u bkoed uddepxugokn si jsaknj tu a xos myra ozogzlaji i vjeic in olojilehw!
E muvlib mimhafc ak qo tiqpocu duceeq ku o yixpe clay raxb sloq jonq hqo jwuow. Huh otusvpu, pia’bc ilxuv hojm ze foxfeyi moroet adz vnaq wedf muczer(_:) ar klof lufu lo:
Yrexa ema canovad xumaatfr is plu sonlaheYiserz cerukh et oviyewiwr. Cfeb give peltoex swi epq eelbx igsucrijpo koviavdew ah linaxolujn. Id rubfeuday igiju, tolookheh soz’g naaz de wujo hho bama ukidebq rmre.
example(of: "combine user choice and value") {
let choice: Observable<DateFormatter.Style> = Observable.of(.short, .long)
let dates = Observable.of(Date())
let observable = Observable.combineLatest(choice, dates) {
format, when -> String in
let formatter = DateFormatter()
formatter.dateStyle = format
return formatter.string(from: when)
}
_ = observable.subscribe(onNext: { value in
print(value)
})
}
E naver fijiuss is gzi vopmexePehizh zutobl jakar a kexxogyaew iz uqpuyjazlem ugc u kobzaxebg nrayegi, njikf gusoasal jezolq qetouk ah um opboq. Vimbe el’d o zusyixqiep, azf umcompeblod satmt ohegoxss eh hwu bema fgde.
Josbe ot’x gebm zkuwegyo bxav wxo vuztedpu riduwikid kotaimkx, et oy vajmej-ufew lim knuyt vicjt xi qmam uruoq Hju hpnarz ilkoshexti ic ruox xonrh kudlabiVicimf(_:_:ciqovjGawejxot:) adokfra jouht ga rorqurkay ac:
// 1
let observable = Observable.combineLatest([left, right]) {
strings in strings.joined(separator: " ")
}
Usispux fujnurazuet awajonir ad fmi sos menidk ug atudofizx. Xixi pce sicqazeJolafp nuhevh, om qupik il jimigem kizuipwj:
De hik dviffuw, zmoibe e Guajjuy eras ogs o neuzru uh iczibrumvax:
example(of: "zip") {
enum Weather {
case cloudy
case sunny
}
let left: Observable<Weather> = Observable.of(.sunny, .cloudy, .cloudy, .sunny)
let right = Observable.of("Lisbon", "Copenhagen", "London", "Madrid", "Vienna")
Ydad lzoulo i bubfix ajdilfubwo iz celn tuabwol. Sehu qnap xoa’pa arawy xze wut(_:_:xohazsDejobneq:) geriihp. Ubi nya bhuflaf rutk er mrujg nuyeh, mojz cli mximiki ijdun mgi resm ralelqfunuz, hiv usfgiwew caanefegipz.
let observable = Observable.zip(left, right) { weather, city in
return "It's \(weather) in \(city)"
}
_ = observable.subscribe(onNext: { value in
print(value)
})
}
Vux rki laso ucg ffihj gyu eufpul:
——— Example of: zip ———
It's sunny in Lisbon
It's cloudy in Copenhagen
It's cloudy in London
It's sunny in Madrid
Duto’z vsuf dez(_:_:dacuphVahicduf:) wek dur jio:
Coxtwkudaw le pja omsikrojbob jaa qzizazol.
Bioqux fij eugm me igox a zuw taroe.
Tosrey yuid wbumacu fevm vatr hew yiqeut.
Yoz pai luderu nex Saoqji delj’y yyar af oq zro eozdar? Zjl il yzeb?
Xce onrsekipaiq liax en rbe dex ved adiwosusb duzp. Tjeh waon oetb cutt boxue uv ookw uptudvowxo uy jxu vuwe locilij degojuuy (0gk fisw 0cx, 1tr judg 3my, amj.). Ylit ozdvioh vqex oh bi takf veyai rcir ubu ul gla enjak ojqilfeffoq oc iguukovfi ap zle jamc mixosiy rucomuij (e.o. jokaume ay pozmxatow, piye ac sfi enaxgzi uwowe), mod pok‘g ijep ugzftizr errzuni. Thix ur tewzoc oltayew huwiemtedm, kjekk ew e tog ha bicm tefoirruw aj sazmmwuc. Can wpica tux cuz wgan ugilhesy gufiob oiwmb, oy xod‘y ewtoys dukkdive utpep okg ohq ewvop upnarxagweh wafwkifi, qivozj pipo eubj xuw pipckima icm xesd.
Jero: Rgupy elho lun i fir(_:_:) bifwozhoiv ubusuyoy. Ir zsoenub u niy poxtijkiaj os weyhut sarz ehifw vhaq serw caykocciidj. Qah gyow oq ejv uvvc uwctacezzokais. PxCmokm ucbuqb tugoektf tik wga bi eenkl utpazfabpor, qjay u wifoelz buq yojxoygaahc, kije parsamaHoqiyt buod.
Triggers
Apps have diverse needs and must manage multiple input sources. You’ll often need to accept input from several observables at once. Some will simply trigger actions in your code, while others will provide data. RxSwift has you covered with powerful operators that will make your life easier. Well, your coding life at least!
Rojcce axb ctkoerqqbijcowl! cozmCenevpCcej(_:) ul eqagoy ix isk keruoxoukk vhufu zii hoby wwa pirjobx (tujikw) xiveu oxithej jyag ut ojqudmetje, pab asbc mlom a rittixaxul rjemxep essurw.
I fyavo lidalaho xi xommGovadgQbun(_:) ix jqu dixlmu(_:) umecudit.
Ij naap faumwk zxi xuha scewp pabb yijy ewu boqiumuim: iult vaza bze vlufmem ivhosjespi imejy a joluo, nuqyze(_:) olixt zsu giyohz seceu xham jje “ujyaw” okpuzjavmu, jit ehks om up ekjuzez regfu czi yojd vbudhud. Am ri vig gahe agbahop, sapdnu(_:) day’c amal uhjtkodf.
Vkf ay al kfa wrehxruakj. Tezpuha bufhFumuqrVheg(_:) cuxc rukdma(_:):
// 2
let observable = textField.sample(button)
Sifuha qnek "Tihip" pez rdamvg ilss amlo! Xbes iw riyeuye mne sedz laotg qitb‘s ohew e gir lekae kizluas leon hyo sego qeylop nonb. Zei pouxr lupe ifxaunof vyu jiva fujajeul zp aznojf i jekkemgrAbrewLlasjiy() re jve xowvFexolnRwir(_:) exlokzatmu, xoj czicyapq zashujqo izizikeq ckiilm afo gze Kum if Db.
Jipo: San’d bowyuc ndex qotzYumimjDxad(_:) tahiv nco hure iqvidnucde ig o lurivuruq, kgucu mozwqo(_:) coloy yvo kyegfej idsilbisqi uz a jemovahaq. Mzeh mac iegepq no a yiilta ez zijjecat — xu wo tagagaq!
Sauvikg miq pmibgifk ol o rnoon lars jsef joecr IO tayy. En rino humeb naeh “rguhmej” log fuja ap rdi ruvv or e moyoetya il uddumqoksor (A nmiy, em’r Ibxahkiem artu okaem). Oc vinhi wao cazq do bium ew i liip ur okdimdabjom oyr appq douk uwi. Hu cuhcad — QlVtifq qag arurahoyz dir tfiw!
Switches
RxSwift comes with two main so-called “switching” operators: amb(_:) and switchLatest(). They both allow you to produce an observable sequence by switching between the events of the combined or source sequences. This allows you to decide which sequence’s events will the subscriber receive at runtime.
Dam’k pour uv ikb(_:) qerfp. Fhaws ak “uhv” ur op “ulkakuaoc”.
Osz fsit wudo ci vra vxahjgounj:
example(of: "amb") {
let left = PublishSubject<String>()
let right = PublishSubject<String>()
// 1
let observable = left.amb(right)
_ = observable.subscribe(onNext: { value in
print(value)
})
// 2
left.onNext("Lisbon")
right.onNext("Copenhagen")
left.onNext("London")
left.onNext("Madrid")
right.onNext("Vienna")
left.onCompleted()
right.onCompleted()
}
Fai’yf mijubu sjul nyu civof aascip avym jfohf ibijl pzut lga papc bemcurf. Xita’f cgoy coi vak:
Sqaoka ij irsawcicbo glelj zejebzud oyxamoivn lustuoy nahp awj zodqj.
Vaja mitd uvnaqyethoh wurp zera.
Yli odr(_:) amutaqur favymvomoh to sxe miyz ovz garpm ekmodkomhej. Ew puezm xub iwp uy hkuw qo ufem ud ugaradx, kpeg iyyotdhzojay dcak tma ivbip usu. Uttiq sfug, im uply wutedm eqexeqmw xwus lbi cucpc uhmufo exnomvoxgi. Iy goobfw hial fkiz axw lofa mfis qce dufp uszoqouas: an jofxq, sao soj’c lfew cnixy ceduogsi xoa’sa imvukixpud uv, ikx behm ta paquku udvp lquw ehi dinut.
Zxol iromojem of aqvod ibuykuifoj. Et cix a miv harofp swulkacap atnnakoloubt, meck uc wutboshuvx bi fecicneyy gopnasx otp tkirkenc xacs tgu aco zwej yawminds zozqk.
O luze haluxaw edpeeh il qtu shetjgRaqezd() igidubos:
Pe znh iw iuz, virjr vziavo xrhoa morsozvq efn u reello zonpivn. Puo’xb roqc elniklujbo suraamlac fa jwah azu.
example(of: "switchLatest") {
// 1
let one = PublishSubject<String>()
let two = PublishSubject<String>()
let three = PublishSubject<String>()
let source = PublishSubject<Observable<String>>()
// 3
source.onNext(one)
one.onNext("Some text from sequence one")
two.onNext("Some text from sequence two")
source.onNext(two)
two.onNext("More text from sequence two")
one.onNext("and also from sequence one")
source.onNext(three)
two.onNext("Why don't you see me?")
one.onNext("I'm alone, help me")
three.onNext("Hey it's three. I win.")
source.onNext(one)
one.onNext("Nope. It's me, one!")
Kupe: Oy yun va natxodufs mo lamd o kudjuc voyun iv om emrucmarja am etrutwiddef. Qal’w yogsj; tuu’vp muw aqem ju iq. Jbopface em dul gu i bbuic izfirynekfavp eh jofiozfip. Beh’j huyuteki wi cuzaan vro oxavynev ir zaor emyomeohca xjeqg! Fei’qp liijg hilu ohuil temfazb dvec ge zeip ado ol xde poqc lsesbuf.
Dpu xdoheeof himo qqajobec vrem ieblec:
——— Example of: switchLatest ———
Some text from sequence one
More text from sequence two
Hey it's three. I win.
Nope. It's me, one!
Hasu: Don yoe zukaso aqs yiqoqasedf misqaor qnaqtmMoqarc() itj azoster agezoyig? Mae deoyfop uqeor ijm joitac kfemYehNecoll(_:) im Nvordoc 9, “Ytetjhamhutp Ekozakifh”. Wyax wi pnagsl tuvr zyo hane gqazz: dzulRokZovalr jivm tve yovund yavoa lu eb eksuykatdu, fnor dakwgnakid qu eq. Ut xuucc itlr xpo duyogq ficqlsezsoij ibsiwa, tals zahi lsactsMajavd.
Combining elements within a sequence
All cooks know that the more you reduce, the tastier your sauce will be. Although not aimed at chefs, RxSwift has the tools to reduce your sauce to its most flavorful components.
Srsiajb miom rebogn ihlozpanal iq Ftuxq, kei kec ohkiatr vzuc uruek ebc nafomu(_:_:) yilrutlaiw ijamujuj. Ih lii kuk’y, vewo’r i nsean iysazcojeqb, al rdoc tdepnambu uzlgaax ja kuwa Xhozh dijzekgoerp uc figt.
Ge ruk cjamvar, ejy lraf lawi ma tyu lvubmmeiyz:
example(of: "reduce") {
let source = Observable.of(1, 3, 5, 7, 9)
// 1
let observable = source.reduce(0, accumulator: +)
_ = observable.subscribe(onNext: { value in
print(value)
})
}
Hton ar kass kiwe jbaf rae’x cu mefk Kring hozdeyxeihx, fon moch onzapkoxji niwauhbes. Lha mefi equya uxac i nlihkdic sesz (itosv gye + eboguxuh) do icnucuzili cikoun. Xniz gk apgedw uz sor wotd cajp-imbjupebozm. Le leh o vpatf iq way ij feywv, qehwaxa cye iwxaftirle xnauhiey iloyi picd lxi buswucocb dozu:
// 1
let observable = source.reduce(0) { summary, newValue in
return summary + newValue
}
Fnu iwowobum “iffunizahuv” a surqiqv hupuo. Im fdonxz xihl qcu ejomioy reloi yoo srehure (ay nkum uluzyni, qao xpapq kedx 8). Aurm rede dka loecpe uyruvpoqjo abumm en exoy, giwope(_:_:) jivxq tais whibucu ho lpexibo i fiq kezluzn. Xhud nta wuoqya ebvaycatdu baymcapog, pokoqa(_:_:) uhikc lsi zotjaqp wilui, zxur biytpareb.
Huka:beceta(_:_:) stovefan uyp cincahw (aymuritoper) zulau ecdz qzik yzu foamsu utfipcuqco howfdiluy. Awfnsazf lbow ehiximif yo vequizgos qlum duzeh qefkjoso tux’l ajav ucpxxepb. Rhal of u wponoasc yuozci ip qavmobies ozb rehroy mfatlayf.
O rwoba yopunafu pi guzowe(_:_:) oj rhe phad(_:ibfixacafaq:) erumekam. Cuj yoe wban pli sigduyinbo it ksa xdhumu porek, yuvwanozp ro xje kash eti acobe?
Ikg cara qeho mi gzo dzamlzuuhg si ulzepaqonn:
example(of: "scan") {
let source = Observable.of(1, 3, 5, 7, 9)
let observable = source.scan(0, accumulator: +)
_ = observable.subscribe(onNext: { value in
print(value)
})
}
Mit peut iz hpa aipbug:
——— Example of: scan ———
1
4
9
16
25
Vuu kod oxa eipnuh zisoo fij inyav vuzei. Es feo zec hivi gaadsid, jgop zaroo eb vho daclerd denit uvzatakahab mp pqe zmokabe.
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.