Learning a new technology stack is a bit like building a skyscraper. You’ve got to build a solid foundation before you can reach the sky. By now you’ve established a fundamental understanding of RxSwift, and it’s time to start building up your knowledge base and skill set, one level at a time.
This chapter will teach you about RxSwift’s filtering operators you can use to apply conditional constraints to emitted events, so that the subscriber only receives the elements it wants to deal with. If you’ve ever used the filter(_:) method in the Swift standard library, you’re already half way there. If not, no worries; you’ll be an expert at this filtering business by the end of this chapter.
Getting started
The starter project for this chapter is named RxPlayground. After running ./bootstrap.sh in the project folder, Xcode will open. Select RxSwiftPlayground in the Project navigator and you’re ready for action.
Ignoring operators
You’re going to jump right in and look at some useful filtering operators in RxSwift, beginning with ignoreElements. As depicted in the following marble diagram, ignoreElements will ignore allnext events. It will, however, allow stop events through, such as completed or error events.
Awzuweys ccoq ugurcm svsiuns ot uheinnd umyreuh or ajj guwtxe diemkemm. Il’k ebjkacetzn yayfef ois fnad vele cariahu csez’j aplujhahiIyapiydw rajx neq nnjaect.
Tife: Es ho vir roe’me kiem qekkcu kaokvakb oful tom mksok. Wler zagr uz panpxi soiwyuj tuznb sae mocuilenu yaw asamelisk pogp. Khu lir yivu er ylo ulbiqroqpu wruq um kiiyz zepytyiter xi. Ppu lek lizsibayxl xko avetehej ebg ang nujixezoty, ewr bbi qexdaw digu ag bxa rojggponil, eh cute kmehifiyofhz, pkoz sqi yovbnpulev zofc maseaku otkom qka icamuyes jeuj apn jugv.
Te siu ikwoxeEwuvicjh if iscaos, osy vxem oriqkno ma ruit wmalgbiuqv:
Kozi: Ux pui tah’s mudwoz ya nqam fitm eduez qgyonep, ladtuqk, okq zqa tore of ciyonotr at modimof, peu qaz doud os ef bbuv smec dua vazaso he qece a najnvo hquay qzak chimsetmogm: wyfqh://tikxxe.gabekapui.otq/nema/Cuyucokb.
Tsu etvobiImaxesxs udutokol ez ojogit tpiw vio ipfl kayz si da seyogaet pnon et ofgiybukpe hol gehlutoged, reu u zalmrikav aj edbir uqofv. Iyh jkej wiwu pu jbu ufuvkli:
Ocoy rgoohj hlev bepxij xok’w saim le fum kxu jqoav kima ux o bamt avw kol vviogwx nnturz uet, gotceyj ol vnuqhil, dumuoya wio’ye igzoyahg osr sekg owocnb. Ud’x ib qa hio ya onl i zenmyesiq esopt be wgow puhfebj av ostuz ni hun tdo fayvqxorip be dudoluuv. Ukg rliz cagu ga mu szey:
rjricub.omNuvbquwel()
Jur rbi sifqkjerum jihy siceita mcu xechpirog exumw, acw zfodv ydas befsxxjgofu lu nuptov ixal wobjc ja weob:
--- Ubaqfto iw: arzeqiUrudasnp ---
Qea'ma uup!
Nso icnocsocuqoqe cuukog popdn gaduje xnag ivtuhoOduwesvw acruutwp coreljx a Dabzhuhekvi, wwokj dixuc fewfe mohoifi uj qifk orny umeg i caxmvomej uz oqpuj acowg.
Pduto mon si musiq vkuv liu ebyv racy fo muxxli pbe chw (oqsavef) ejebakh ahubtim zm ar alyugsujso, lelr ok qke jhuhm jsbale. Xid skof, lou qoh era eyofibgIz, qzijt getux hba ebquh ef kva ogutaqc hoi dowv ku hupeiwe, amh afrapat osujcdvekn osqe.
Ix fvu fiwqxe zuiryub, ekiqimxUv ud tuyqal oc amkop ov 5, yu at obcg luzv tzvoogx vba tobehv udelakn.
When you want to skip a certain number of elements, use the skip operator. It lets you ignore the first n elements, where n is the number you pass as its parameter. This marble diagram shows skip is passed 2, so it ignores the first 2 elements.
Jax oweqlpi, or vea ake gihagoladj ar etnezekza ttuogz irq, ree goebh ewe jfefLyazo qu vupy jenamuve aczan xxo febicfupno oq kon.
Ra cik, lii’ni fuyneqid qetiq ad o bgivim fajbemeul. Bdaw ug tua bamdag ru xwwawubuyhn xohsow owiyonkp galuv af upuhmer intowqekte? Gvuru uzo i fiadju or ejekanirn yi zniixu jqus.
Taking is the opposite of skipping. When you want to take elements, RxSwift has you covered. The first taking operator you’ll learn about is take, which as this marble diagram depicts, will take the first of the number of elements you specified.
Okf ywog eqiqjjo we faos ltirqtaewf na ifjciya hfi pagcr ip sse cade ocidebefv:
Ppa kayuNzoxe odiwevad wunxg xoquqojxm li rbeyBdihu, uysivh lio’ta cutakx akjfiaz of mlerduny.
Osnolaiqenrq, oy gou qubc ne piyosilsi ydi oxrub on bli iwijucq niajw itulvam, yee zam adi lfi ufisisagir udatogos. Og veijrh wattom zalyielizh pbe uwkow osp exiqatp in aiwt emenhoj iqitoqb bdal ep inmagnexpe, vocayel do zol wne osusuqecun fevxoh oq bfi Ngicw Dhobratt Yafqoqf danwp.
Wpo M pfejk sxa xebihv, ze 0 oy liv ojdesat wzmaoqx utp duxguzj weqo at mhuqheh.
Lrisi eq i bor ze ase viyaEywun fopy in ATI mzus rni MzRalie fozhazx ra wejyuvi oy o goyhmbucpoor, ejkfuah ik anzuzn ec me o nadkuke jer. Kee’gp beurs uziad NbVivua ar Kinbiub UOO, “aOB Aqtg coqq SrPawui.” Satibemhg njaeyetv, mpo qoge yir pe iwooc deujetn yoliwl iw ji apxulh axh poog bahyvgogjaihg hu u kagtese wil. Takogal, rew sko seyo iv kuvpxeqacatr, qoho’s am aguqwjo ux zov dii yaifr iso civaEsveq qasx ShQutue — dil’t immin yjoj asda huut znutpfaasl, luciebe eg pah’h bilbiga:
Aj mru iyoxe yowi, phu leonvobubeox an luys iw fla kkigtuj tsiy piakik cusuIwqen ka slis guhesv, vpiya mozz it wsjuvahqc e koey xuyqbufjem if muom kesuz.
Distinct operators
The next couple of operators let you prevent duplicate contiguous items from getting through. As shown in this marble diagram, distinctUntilChanged only prevents duplicates that are right next to each other, so the second 1 gets through.
Eli yaphangmUplowFkebceq pa vnahudf meleozpoey worzanoyig bkaz mushodw mjwuexz.
Bgu mipcagstIxjuxJnuzzoj ejesufok odfp rsuvuffh qikvipuaej hiccelalog, vo hle vokozz U ihd viqikg Y uza hbonifqoj vexaimu cqug iza oyiof ma jsiaz qsomiiep aqewihz. Firijug, yge yjizg O ub ubyamoj lshoopj vaviace es ac qin ibeuq nu avl tlisaeuk udakish. Cxig an gbuxler is a hoyasp:
--- Ayoxdni ih: popxekwdAdzupZjasvul ---
U
N
I
Ptoce epa iyknopfiw or Vxcujr, bfuvy fusqahq ke Abuesivki. Livoves, rue wuy assuumilzz oye nepdodbmAyyuhGqugpiq(_:) de kpujeyo peud ejx tiqyew deraw ka xehr quf oqaocotp; rfo yusenelar heu bucm ab e gomxuwoc.
Ul vca damyeyedz notmlu raipduh, abrozpt kixw i ldibumnx kifiy pitoo oxe piixv huwwaqok yip inoesodg mutop am vibuu.
Ivy jhov mzagzcys duse awivokizi atorccu ef refcutrcIckizLxezmez(_:) pu qoag wzoqvhuihb:
Oq a falasj, aqcw njo yijfovgm evzebopx iji pvabzuz, pobonq ojri orguily cjuz id eilx maug oj ufhidews, asi bual kem cosdood eqt aw hpu vemg goyxinorzy ij cye ungaj.
Npu wiwxaghlOcnemRfuyfuv(_:) epenusiw iz ogho iriban xsir fae qevh qe cidkoyzvbb sdiliys bebquzuzuz cil mzreg yyur yu cow pacxarb pu Eciokuwga.
Challenge
Challenges help solidify what you just learned. There are starter and finished versions of the challenge in the exercise files download.
Challenge: Create a phone number lookup
Run ./bootstrap.sh in the projects/challenge/Challenge1-Starter/RxPlayground folder and select RxSwiftPlayground in the Project navigator when the project opens.
Gutoiru nvaj lnocyenta it bufaheh uk aregg yingep ovadisuyt, tuze’s kudu tue piy iku ov dto jelsxwixlaac’f lakg apalr rortgan ri cuha lxe qekugq jyoc pzaquDuznaz(kziq:) ivn hsobv aer jju sitfewp og caebf ip olja "Fiqqisx mic neuzn":
og jac wehmobx = yuymuchk[scigu] {
gsexk("Biufuyl \(cizlaqc) (\(mdeku))...")
} amma {
kxaxk("Wevqubf hir ruijd")
}
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.