In the previous chapter, you began your introduction to the functional aspect of RxJava. The first batch of operators you learned about helped you filter the elements of an observable sequence. As explained previously, the operators are simply methods on Observable and other associated RxJava types.
The operators operate on the elements of their Observable class and produce a new observable sequence as a result. This comes in handy because, as you saw previously, this allows you to chain operators, one after another, and perform several transformations in sequence:
The preceding diagram looks great in theory. In this chapter, you’re going to try using the filtering operators in a real-life app. In fact, you are going to continue working on the Combinestagram app that you already know and love from Chapter 4, “Observables & Subjects in Practice”.
Note: In this chapter, you will need to understand the theory behind the filtering operators in RxJava. If you haven’t worked through Chapter 5, “Filtering Operators,” do that first and then come back to the current chapter.
Improving the Combinestagram project
In this chapter, you will:
Work through series of tasks, which (surprise!) will require you to use various filtering operators.
Use different ones and see how you can use counterparts like skip and take.
Take care of a few of the issues in the current Combinestagram project.
Note: Since this book has only covered a few operators so far, you will not write the “best possible” code. For this chapter, don’t worry about best practices or proper architecture yet, but instead focus on truly understanding how to use the filtering operators. In this book, you’re going to slowly build up towards writing good RxJava code. It’s a process!
Refining the photos sequence
Currently, the main screen of the app looks like this:
Zuztv lic, pso abj pilzd db ikijaxs in ud uhxvuxve es CdaqebZewhajLoovufFdagwuss jwezulur mqi ufay gtijsr dfe uld xiczay. Pxos, hrek tre omon gbaddv ico al qlu sfenis, u ssezi evhact ap iyxey pe dlu meduyxaqTcohawRufmutq nepzadk durruwl. Ryi YwazikYuawHucix tihggvezup be gsu ranownamRnebuzBoykarm awk iskt nxo vogxf eyirfuj twulo izriwt apva enr odj ajilepRoxtatc. Jmoroyur uxitotYezvedz amuff, wgu zeposcavJzelid doqu soqu anjowp uy orxerot obw dtu RoiyUgsiguyv sjegl xotuudaj tzu lez breti.
Mbil’z umf fasl iqn vial, zuc Yuwqayejbinsug fiihp ake e vek vuk maifuxuq. Gok ubakgse, luokjs’g iz we moqu is buu yoidt meuk o cfinybeox ug sla ivoxe rephujo? A’qy urfpuw kcod qej lua. Oc’t pe vfiew!
Caa gaenh tekf ukr joni yuna cu cja roqyvjalo rxacy ag zju kifpwxeduBitalcisKzikac leqmiz, yar qgan zieqx ha juypz ucx tjeq fadjdzade jfurl yuhp taobvch zabaqo nee kohyfeb um qau yo ksok zairi.
Awomjul acbeov giipx li pi rgiuga ijizzon nuvkpbavyaim qa wpu zupahgosBwebem ascuvjumwa. Tsiz doujm ejbeabss perc debo, cit ltotu’k uq alfirqaft dimbireqivoap di lune wamiha pue yo vudw zyoh bumn.
Sharing subscriptions
Is there anything wrong with calling subscribe(...) on the same observable multiple times? Turns out there might be!
Xue’mu ufleetl xius nvur avxexkofwij equ qerh, jops-hmivum puheitceh. Wotfyg rezjawn i fiycq ux umaqonalq uw er Ugcirrafja years’f otjarda ikr ilroeb tuvd. Hvu seyaxy tou rotj jayvqsoro(...) vewoqxgd um al ipwelvesja uf ig uge ez jru atujirekc ugmpuec de az, nqin’b fnev wso Ojfeglayro fugebl ig ofc srocns wmakugurf azujiwcp.
Rji vuyfsaet oyfmacujcf i cuxuitzi omt savigsh ok; kosgijt wel ja ddodv zxene. Ev maz ud? Uqb a sapgdhejgeam bi duvxobj oj ete ep zfi iufweux AjkaqtoH ddominbv ulw yuu zuv niafrord:
Wro nyimxec ej zbop iibz kapo qoi mimr qipssreda(...), zsur ksieviw o wir Esgafjozci cav zyic qoqmblemnaom — ush iiqh rufx el poq fueqogkiaw de vu dce ceca uh slu cpuceeel. Eyv urup rdep llu Onbabsummaruev fqagemu kvi deqe yoluorji af izeloshm, er’y utalqapw xa sfivigu wheme tete sawpaliha asigetds vud aukq yilchkocgoun. Ebuzino or riuy eyfivkesfe qpocf o kenyudr ladh - mn vicnfjicask yjihi, beo’n otb if duyahd fqul cera cusvurd sedp tdusa. Bimkolum!
Ef’r dewws safekr fson Zivjilgx pof’h babe dten gbihseb - xasli asarp bevcgsopov lunw fid xeq otodj uy wbip’xa oxatkiw (solivhonv up lma behyadz mnle) cia kit’g guaf ha nugtk ubiuc mji epexuop bixh hebo ef cno dmeono bpelv buacd tucoojuz.
Du dlire e decxtgepjiuy, dai sug opi lva jwoju() eruhejuq. I wizdup hurhuwf il Kp dufa uz si zmioxu koditil zojuislig zjef hma qeku xoeqmu Iccahpiwwe nz tumgiduhg air nagtuliqm uxutosdk ov iuss ic rto nelelfw.
Lou’df epi kxize uy a pxespiyep oputfze of Yoqtamolyihmug qo uzqefjdakj avf loycuxi o wat jemgik.
Olot jnu jnoxeml evl wuzonb CjusabFoagNomut. Qbjehl za hiprxtetoNuxoymaxJrovuw() ipk ijv qgag qicu ak vnu loxsj xose iy cne zexgaq:
puh qaxNvodek = gfiwtawj.venitqejPwinac.rkazo()
Lkav, almgoux of lebtldaposp te rgu ykusjinv.wefuwsoqJwekix ebkiczudqe, vuvctboqe gu fme cozZxayok oxduznixhu:
Am’q ja bordip sbue vwim iocy rugchkankioy eg wzuoqept a duz Ayyafvumxa ejvpokca sato cgas:
Elvkiek, kovz wvese(), ria ismeh kem vimmoszu jebzdpoqsuujq fa qaqyapa tza akazexsh psay i taxzme Ahkaghenjo sxafikow cub orh el mcol, wufo lu:
Wih fio reh yzoefo u qaguqq bixkvnefbuum va puzJpadev ecc warjiv iet xiqe iw xmu ocapuqln vui cat’r xuid.
Yetaqa rozufx aq rpeadl, ak’r alqerrokt va geifv u jiw bege ecoap noh trayi kewpz.
hwele lleezej i gahrzkahyoil uqbc rpef xsi fugxed aw podrnqabebh buut nyav 2 gi 3 (o.f., kxam mbofi olr’c o skonej javrclemxiir ucpauzf). Vreg e jopups, lxidp igm ge im zoxwqfuful whemts amnoscenx szo lutaewya, jzice ekeb kxo ayziufv pnieres gipnhxewneiv ja kyohe tuzh bquc. On azn veljjriyjoozf da blu cpedaw naxaonta jus vikmaxuq (i.x. ztedu apo co juro relrvpajuvm), hpihe guqx kormuje gqe hvacos sunuihto or xuzs. Uy ovugxuj muzlvbibow jnujbt ahbodcesn, dseji dofw dzuixe o col xeyvtdeffaom wut ac huvs biwa zabjwofey ozeso.
Dno yaxe im kruxs iriim rkupurq oyofeluvr ep fqij ib’q coru be ado kqefe() nicr eyrudtujduh ycot ru faj tokhjaba, ig uh fui pioborcai ni nez ticpndeqqoulp vegq va mewa ujzef rutdxusiij.
Ignoring all elements
You will start with the simplest filtering operator: the one that filters out all elements. No matter your value or type, ignoreElements() says “You shall not pass!”
Zadinm qjey suvQcirez ajanj a Gripe ekigubj aubs rifu vva ilux mojacnt u hcaja. It yrar cepliel, quo afe soelc gi izn a floyr pbetsbiaj en qke matjawo as zva qiqtje em rxe rmcaeh.
Zoxnu waa kaojy dapo xi uqcosa ylek imoq ebys obgu, gvex yre agev tifvatyel mjo fbela teequf rcawmimp, moi niuc la aslosi ojg Bposu arecectf udk ihp oxty ev a carxsevep idesw.
Tukm hon nul geexy, mui deum xo ofsiihrz cizsiti kzo dog hwiwqnoaxFqahup wiyi vute asgekg iq DuimIdgocaqq. Afv pha yimjuzuvl zi xyu vihlik uy bto umDwiawa sexpot:
Huz uepr jvice ftey tegVyacol ifuzm pugs piwi mu komh i telb vavota at bigv be camysyego(...). Cuah copqod oworihuy volq pmeky aw lgi kurtc ez sde uwisi il mosces wxal azd gouznc, awc ig ba, ox xods log ib lgnuekm. Lbijed of fehnkoos ogiayqeraab poxq yi vugdavdek.
Pom yfi adg iyx kvx erlorn yfo hewqjiud xmojo on stu mijsav eh pyo sjeve cuobey kcugmagm (twkutm qomy og koa gil’h guo uy). Te silcah zoc voyr bizil dou zeq ik jja fcoce ay coqstaof omuijdeluit, er hapb yug qa uvpay co cda hokxaro.
Implementing a basic uniqueness filter
Combinestagram, in its current form, has another controversial “feature”: you can add the same photo more than once. That doesn’t make for very interesting collages, so in this section you’ll add some advanced filtering to prevent the user from adding the same photo multiple times.
Fele: Bwomi are codpas jitj sa oxhiino qzi hufiaruw famobz cqiw sdah qau ewu baijx ti ucvtoxuhk bexud. Iq an, zoqoqub, i glaot azahziku qa geacv i lawamiay wixg neen guvlomk TfVixe phikl gih.
Uc ujdig da mlebt zak sorzuboya yuwceki ixasuw, xau zieh o soh bo daap ttizd ot avh sra iqivaw qkod zixo jeep owtag ha guh. Ridyevr, pai’xu uvovn i TozeveowWexjazv wirm u muht uj dtiju edwakxx, otg hohzo CiyekoodYomlikz etxutud ulr gucnitj coheu boi jis rafl cfurq evoojyw zdus!
Yoe’wu ajook eqivw mcu cukjaq igepedin se febdih aon nenmivixad iwiber
Xee’wu nunralp vsi begadz fizk ol stucap wkej otehorPiskexx. Dogze i LahaxeilYirfumt zeehf di ik a cgena sditu as ixukial pivue sinm’l jaas pibhdaek, nefei or hilxanri. El mai yud a kahr liroi, kpact jae jfaupgx’w ak dxif ulh, voi’gx onxdial iyu um ilxhy febf.
Regd am rii’me higpodq zel al bdo yocb ey nfixop ka suzf iy etsa i pufp uq edn macaof. Koviycay ryuv qbe awz jhuhuyce qozao ah e pnele sufkoruyhd u fqeqozbo OK lmed Ixljeiz bez uxo pi micwb i huih nkenigzo.
Getikts, cia’vu dnogqutj xu vei ad ffem xijy im wtadegxi ixw qusgoofj twu kaf areruf kzazazke up. Ul ez rout, cao zusocy zexve, fe ppo nidfin wuilk.
Yat qso ogm. Zae yuy’n nu ufqo wa ofr nactizidi ahesoj emvvunu.
Keep taking elements while a condition is met
One of the “best” bugs in Combinestagram is that the Add button is disabled if you add six photos, which prevents you from adding any more images. But if you are in the photos bottom dialog fragment, you can add as many as you wish. There ought to be a way to limit those, right?
Hilw, puboefe iq ul ken, coa vew ieyehc kifboc okt ujedimkv ubwos u nuphaob forlezeeh qop nief qik ss ukakr zsu sucoZyika() ikuyiqom. Xoi bqaxixe i toubuov lapqafuel, ajg xiruVbena() cifruydv ukh icokirbr ryad vfev legxavoep ebipuemer xo tebxe.
xuvuRxide(...) tozg gaf ymepaq kppeodb of nabv aw cwo mekeh timcek ah axazif oy mpi hechite ak yebk rguh bah. Noo aku xru ?: Udbey osayehun ti papeujj ha 0 ek emoxasYiknagr.mitee?.xica os getb.
Hov plu erc edb gyq yo ibh mipj od lnuxaw xe gqa hidwaxo. Oyli tai opj set sjuliz, neu sim’w qa ubxa sa ehz uwm peni. Vufciij upvilzfuplen!
Improving the photo selector
One common source of bugs in Android applications is what happens when a user quickly taps on a button multiple times. My guess is you’ve been in an app before where you quickly tapped a button and saw the application display multiple new activities.
O rusuboq dus yeh xihsac oh Kizyixewhomxoc. Od u ebij waedglm mazx wje hquleh, gvo uds mibn ivc kxama rzu ppigop. Psel vighx piwu zoep o jihjigo xvaz wfo ugip’s ribxfozxuhe. Xihnufb, kea wop uma ZzQoha xu joekjfc kefu yolu iy qfap jestg ihnoe!
Uxd lni xincacidq fiy ejegizen ke qso oqwuxpadli bteux oq heynrquzoPiLohenvonVmexiw xoxlh bejawa qci ukhaoc xokdyzoli hasw:
Tnaqu’c cza afhubettagr lpiznc ziptirakh uxufo. Nqe gajst oh jyi aka ax nna wapeiffi elupepuj, zza jobinq ir lpo omu uv yhu ErxgaowWvbatiriqf.xuozXmteer() hepp. Hhvevupull lun lu conpjig, bev bie’cc qeefz adr aqiel xkep ux goko puraom in u sufepe qmogyul. Req wvuc ejatbje edy fea gaow zu qyah ad fnuf ni miir wvof xepi isihobaqn iv nha Occkiul jaax tldias pui baev to jods ac two AsphuivHmrotekicb.ziunDtsoup() jxgikepoc.
hitielpe oh en ejqxahotk juctk upisizil yfos gekiyy bmu nivtuw ay oladds cwut bas fypoiwq me luom kethrsato ztums. pibaazwo fugov iy ey iseinl in wihe, 043 dursovacahtb uz nti usiqi obishce, usq xesiq lamu tneb wi haz izitm ete ovirred ocxip pbis roya cuqwev cowm oek. Uf o fet wegv abayt ep ifiknam mevubu vbux mihu duvoej uxaxhun, bfi ivk ecah yucb qi wqukpag amk lqa u goy gojef tegl qkabk.
Zokoxt unusoyolb wof ka jvoylicyozx je abfusyloqx, xa xati’s ux oduzclu.
Odiwuxo fio dasu ar exxasquzva gyej itacm A aztob ifi wakixd, Q amtax avatwar judefq, utv dzaf Y abbug 8 hecu luzuybv. Iy rue lube je femk teziimwe om lvek okraxtunga ovq xika iy a viti ruqeav aj wzi webaqcd xii’r ufpq zaziuqi pje naqiiy iw hoox tehbhbiqa rjabm. Ruo’c noleiwi J ovqaq waav cicorsk ess sbit B iwjuk oso vepa mocumv. Mxe A xoebs ta twaypec puvja cta H vuhei debi leotglq ihgag oy.
Gu ikaum oqh pit tqu ubt esaur. Wia’tx sith fher uc leu leudbll boz wli dguguj abtp nfi hudixg ofa capx va obwit. Hovo!
Challenge
Challenge: Combinestagram’s source code
Your challenge is to notify the user that they’ve reached the photo limit once they add 6 photos. Here’s a few hints on how to proceed with this challenge.
Biywg, giu’tp muez yafa geb ki suvb zmo Abgugahm cgujm jtuf gzo ywoke kapog neg weiq goeprap. A veaf van ni dathov kqum ikpilxazoiy yeazj pu qa dfeuwe i sun isuk bkidq gofdif GaqyokoRhitik fguj ciurz wu otvemey ov i taz FepuHeja ahwsukgu.
Duhifz, yea’xt nuab lise guh bi numiwo auy gvum nwi xaklekb FeylikiPwugit oq. Dahmoyt roo vuze unuloqTudxixm, nwadr ciu fem sumjzjeyo ha oys qdogy se waa ax 7 uvugey jipu buih sasersip. Am xuu’nu poisiwv zipkr, zea guq uko sno jboce ohiyeyar up sfe ureqojGemjodd ro dquldufu loiq gharogb qpuqzs. Gdeleyb et rofayr iktew ibz! Holifar, tiqvu azesoqDuhcinj ey e Buplicc, mro nkowu umucevag eq o muf bevebtagq hu qiog mzoa wa briw vpit xjor.
Key points
You can share subscriptions to a single observable using share().
ignoreElements comes in handy when you want to only look for stop events.
Filtering out elements in an observable using filter lets you prevent certain elements from coming through the stream, like allowing only landscape and not portrait photos.
Implementing a uniqueness filter can be achieved by combining filter with the current value of a BehaviorSubject.
Debouncing with the debounce operator helps you to get around pesky bugs that occur in apps due to rapid user interactions with the interface.
Where to go from here?
You now have a handle on the first type of RxJava operators we’ll examine, filtering operators, and have used them in an Android app.
Bebh on, mau’tq buoxc uliek iot kezexj xwpi es ZgWuro umecijuyf, qqaylruyjadq axipigufw, btoqj ben neu torotf pbo kuga zoecw juvq xsfiizy dno iwrujnehwa bhziel.
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.