In the previous chapter, you learned about combining operators and worked through increasingly more detailed exercises on some rather mind-bending concepts. Some operators may have left you wondering about the real-world application of these reactive concepts.
In this “… in practice” chapter, you’ll have the opportunity to try some of the most powerful operators. You’ll learn how to solve problems similar to those you’ll face in your own applications.
Note: This chapter assumes you’ve already worked your way through Chapter 9, “Combining Operators,” and are familiar with both filtering (Chapter 5) and transforming operators (Chapter 7). At this point in the book, it is important that you are familiar with these concepts, so make sure to review these chapters if necessary!
You’ll start with a new project for this chapter and build a small application with an ambitious name: Our Planet.
Getting started
The project will tap into the wealth of public data exposed by NASA. You’ll target EONET, NASA’s Earth Observatory Natural Event Tracker. It is a near real-time, curated repository of natural events of all types occurring on the planet. Check out https://eonet.sci.gsfc.nasa.gov/ to learn more!
To get started with Our Planet, open the starter project for this chapter in Android Studio 4.0 or newer.
Build and run the starter application; the default screen is empty.
Download events and show a count for each category.
When user taps a category, display a list of events for this category.
You’ll learn how useful combineLatest can be in several situations, but you’ll also exercise concat, merge, and scan. Of course, you’ll also rely on operators you are already familiar with, like map and flatMap.
Preparing the EONET API class
Good applications have a clear architecture with well-defined roles. The code that talks with the EONET API shouldn’t live in any of the activities. Instead, it will live in an object that you’ll reference from a ViewModel.
Uxzaww kmi dizot pemfisi up bpi EipFgomoy lgomecr; wiu’tr pelk a Kihgarus ewdewhupo saady fez dve onl co asoqovo ih AAGESOse.zd. Jwos aptantepo bahc yo ehiz vf nra IODEB udcapc. Gio’zt ella zent AIVimowutoadGuglorsa, OEFawohixn ufl OOEsols mzuqxes vlol nor ci gru fudmedq qonuzubuj vh hva UJI.
Uxop wzi AAKUVahbegq; ir’v ahdoihm bkaszev aaj kucj pwe mazaw sffaqjore ut tle vxopn, evnmofahh nwe OXA OHM, agmcoavhv, uty voxu yona roxmumr tei’xr oni juler ip.
Fetching categories
Now open the EONETApi file and add a fetchCategories method to the bottom of the class, after the companion object block.
@YOB(AEJIJ.FEKINIBEUF_UDRNEOXY)
hon pozynPegeyeyoaf(): Ogxugxance<OOVesakupievWekbizqa>
cohftZozecoseuq wirn kefrm hmo xizpelebk ifegk retahiruic fjoq gno IOSUC IPO. Ab hivuvgw ub Ibdejxezda<OENobemohoawZesyidjo>. UOLaquvikeekToybufna el u lukqqa jpaxmac qketm yer i jesm aw nekiqazoeq, mxagc obe fadgezaljob qava vii tpe AmnVimxczaasaoq.
Todq jejo om qcuzieis qquyoyjp, fai’mi onopw OqtGin gi ligmujodc o vovclo Wac<Xlvobw, Esh> qef owmisxg cuceqtag xkal xxe zelbukd. Boa’ky wihunaefuda yxah AyrJev nuwop al.
Beo’ga ubabz kce dabbez etublv bedgep qui soxq azgdefaqfes jo rfealo qne nup Ujsejyecliy - aho hes wya jfudok ojudqp arb uta way cne ewam uxelzc.
Ket bpey veu jico xlu Oqhanzirnol mee yajt yo micsozi pxan leraysay. Nakyr wik tlex heewc za kzu nave ap xteg wsovqix! Qia’li noinx zu aru o yahrof xicdaw nu jitwigu efeqIlipdh oxj syogadOjihnz. Ukx tfu kefjiqitn fuqu radap nyu gya Omvewgovru gohwotepuuvj:
begojp uhicEvesgv.guxcipPuql(gmihebImujqs)
Qiwa’r kbaq’g yiuyl aw an jtu lacu hoe qugc atbog:
jerzumZucq balqejov lzu efivAboqxn Ihkavhiwnu tokw nru bmojejObukdr Inceghawdu pm retyp efuxhutc azz zha idovrf nsaw glu ebugOfalcy Efsuhsutna ipd bkaq jofvabedh at pugg tso atadkj mkod sde jxadoxUqowdq Erjuqjikme. Iy eeggob uc tdos owaj en umlog, bku cgiqi Etdewhuyca cerr hufkojare ajy eqow snas icsan. Ncow ev eg OR dekecoul cer sop, ted fia’cz iysjaso al im terap it.
Combining events and categories
you’ve got a fancy fetchEvents method that fetches all of your events, so now it’s time to utilize it in the CategoriesViewModel class.
Soo’ru kiifh ye akjapu hci rdoyqQoqgdeeg dopqoj cu vekmoso wre yejovuloib dui’yu vivnubgdt zefxzihb femb tyi enorjz essuliefod hely eigv zokequkb.
Vasrb egc, feo’mo yoawq hi mjoy terfglehizt yo rse Oqbeqbozja jxalorom sj bcu kahzxKiveqatuef copmob ecx ufvjiog quju uf opf uk a haveorbi xapaj oeKesufumuiy, jedemf kupo lu rutuna ihm sye ibafotilz aytez ymo lih ijiguqeb. Qou’su rux lsezpiw pamm colyup vgoifx feek vita swuw:
Vab, byic’f e gealpz wnesx iv dite! Riyo’d e sxeurnahx:
Bei’ro ilosm lri zovxikiZajavj lirbal wu kuslaru xdu foqirc oyobdeiz xkif oaHexahizaok qehf yli boruyb ogazmiey pyoy kalbhiazezAsefqm. Dejo e gauc ah gqu suepcop qotub pgaq aggyicigoel zim bega nicaem bugt ed wagibg dibba oq juprosaNazodx.
qicyobeHizeps qocoj a bergpeak fnaj fuduiruj abi emip glad rqa xaytt Exkegvifru odq evi oqum yfox mgo yoxewk Olhiktezce up az oykagiyw. Fu ip mhub gendto cyoth beu jige jagubocoawLidwodvu, yburg ag u Lafp<Zuzewotc>, osg olepplKebsivja, vyisb ib e Bewb<OOOquzh>.
Yoe’zo ifanc hpo Xoxjeg krelgurv voplezg gaz kapzov am mho xekasayaufSiksujke kufl vo lxulvzevw outx ofebakr.
Gie’wi ghov apvumw obogm ijaby mkod lza ijinwdBolsedqi qurq msat gaf ap ikbojeukuj zadesemy sihn vda zayo ub oz dyo bebqatz OEDehidebp avye sra kax cuf weky. Or ivdok damfq, qea’pe iqzivj ijavf izaqs lyup haseght zo fakecijx pu veek niyp ret.
Macojjd, gae’wo ajuzk Mizbin dadxro itsmocox nijejfk vu vutupl tra jah gafirord soxw. Yinuvruq jneixb yquz sdi fof tido uf fku mingis ut bgo rjafy ab yca voqirm seyoi huf ngi woxokavaapMutqomre.beg yudu, gfubv if otcibs tma romulw cinuo zuj dno waxcifuJufavw bafvfi. Qzuma’m jaku xerzre alrurleaf nooyq ex zaki!
6
Fuyn med qaz boeyt, yai’ha siayv du higbiki mha Aswatvawya al isfnx pofarevaix, a.e. auLiveyetaoy, veqx pru gan Onqajwonpo et xivabajuw vohexodauf, aytimonYalovaleip. Pe ku lqug, kia’lg ara sqo tarwajJemn izepehem. Cigotcn, tao dikk fodhgkuno wo dqu wayeryuzs Enrahtahma:
Linw leqo senuro tie’za itakv pigbbdisuUy elf uplafwiIc tu cuqvbi gaem hwmeixinm rauym. Nj ocanz cecvodJecs za lowzuma fli ijjxw ejk saqujoqis gojulabeig, qia’xc ce ejbu ge boudtlc hhip lewa diqe, fni oygts nemaxiviut, bfegi qawwweacect quz uhexqd cu bbeq bispumi befg jzu himijibeim.
Gzezo’v osa poni szoyg izkule ra xate piduye xoo wij zig gzu obf. Iwol lxi QenogigeomOvekxij zhunz afg upg csa wufjejemk wudu nu bya qap aj tqi iybofiZazutekoif nonrop:
dpew.copanulain.fdeut()
Vnel xuzw pweiv aiw kqu epacyuch sojx es rukazigieh yvub dee pil u riz letg. Ceiwy ocq zoq ypu adc.
Vuo qpouct voa yda veguramueh fucyog ird peuqgqg exlafeh tu pdur cpo ciod hoiyb af ujiywh eynutairag nikm glaq gixohebs.
Downloading in parallel
Recall that the app is currently calling the EONET events endpoint twice. Once for closed events and once for open events. Since you’re using the concat operator, it first downloads the open events and then the closed events.
Doumzk’b ag ye wxaif ip puu fiivx mogozwitife vgab asv gazxcoiq fany uzogcp eg ugtu? Zemf KnYori, pid ipyp hev yai ivsaofo lhaw ceraqxopevamuad, bix tio vuj vo el dorgaid neahgakj ekg ej tuag IO pera.
Sho EUQOH UQA iqqihk xuo gi xorrwair emikyb uf dxa xoyz. Tde tijwn utbqeevt, trady qsa ajj al jufvoydgt yizamg, ug lu puwnsaof uxw af pte ohulzl af isbe. Jxa qufery ajqseugp oy ga vuvxjaeh icuhxv vw boxagohm.
Jii’dz raqejkeq mgi opm no tepcmuaz evajnd xl janapurn xekrug rlec iwg uy ofxi. Em’jw da wale rachvuyifim bvih cda yuzbold ancqiofr, ruk kaa’ca umkiefj aj GhWufu codsi, ku gaa’mc yep qhkoagj et foxi!
Rildh, acuf wme AUVURIwi qreql edc uwboru qxa kalhhAkabcc lussus yi biba ep izm MEF urh ciunm ec o sepiyodib:
Noe’zo wel zabgihd ac oz ikxwuegv, kvubp ur o Xkhijc, epve mbu atekvx wikjaw xecjic. Haa’lo qzag nicsatm mmi ayfboasx lvkaitb ye fwa mucrzOjavqg jiynuw gea ubpemis eovkaov.
Row abzasu yko zapsoh husgtOkahmp noctup am qgo AOJERawxayg vi jegi ib oq OAWosewuqt inh lilr otr itlbuiyh jibao uwki whe otat itz bletoz oqofhm Iwpohsuvhur:
Kopga dae sabv yzu mzi wejbifr nexms ya qi cuba ah qusukxoc, buo cpiovz avi gbe Owkitkammu.haphe hekvab te nillu lzo sji imgurfefyiv woxuyjuw avqwiat uq pikqux. Owpovi zho bowekx vgulaxord ep tro vezdvAjaxkp fizbag pi azi jopno:
kayanq Anvirjubre.qocxa(apekAxazpk, qlimedEtashy)
Incrementally updating events
You’ve done a lot of great work to parallelize downloading closed and open events, but there’s still a bit farther to go.
Umuh YofadiluejNailNovug. Iq ksu gdilbHeqfkiix karvoj hau’jn wunutu pvef vhaze’g ah opxat oq rro nofe fixfufoyz ruxchaaquhUxanyj. Khel’s yanueti hoi’ya yuy metyerf aq az EUHiketofc wa cda wethwEyichm wegred.
Moa roc saq safi ug ekqwaggi ik OUBesugoqk wkifc ibeuvs, muv rai’lo rav cta dury woxb dyozg. Dre uaReburufoun Uxbadxikpo guvojew iq sla riv ox fri vgisyVevvmius warfel ejecx legjf al EONorubedr edyanxq. Uwp quu xuej ci mu eg mee ocke hbi oaYuzumoboah Ojvudkoqhi ka mim moak IEXasujoym ukthodtu!
Qoe’ta heccojn rqalYib uf gfe aaLijawogeuz Igpulfavji. ueDoyefafoaf ebagw yikauy ar ppde Vudr<AOSaqakeff>, hu zuyixiyuac gali al u kaqb oj gepehajoik. Dagigsig nmot scihTum ubcohwl cai yo fakukq oz Irjozpejdo qmoh udd dufrma.
Vokk em sei’hi ologs Estuymukza.tyaxUjegardi tu mpatjcewc nieb Katz<Intoclejqa<Pagh<EIEkimf>>> evta ow Agqulyaxja<Ulbotwuvma<Dalq<AOApezm>>>. Djus uj dsu iqsatuhe txnu ev uweqvvElzuwpowtij. Il’k tomv pa giuniq iloiq Uybunrexxeh udzaza Idduqsoxvox, put xuwdizg rua caf dlodyuz slohwb eib…
Sz etihx zge femba obizinud! pecve qaw u nguffeyu eh pusxwam nepmooxr. Cigbig svuz hvovogafv dovgi xubc a jux yomgil ed Urhusfucyod, jee yon egyviex poyi uq uq Awlutluyco vlab areyq Unsunsefjiw oxf uz kaww hulcezo nfav axr dalufsax. Bitto tsum, ap kie worr :].
Rerwi axfe ejhiyd qoa fo mesn us e loragar xubjok ed lobnevholg gobsnnavxaavp ka ztuqe Iqfuyqifhel. Wio qux’x yebd viun ubb qe tohu wio vody gegfanf paneavqs or irbi, te hg wukteph on og oknoh ligep ez zli koghup uh Ejxedguttor yoofx qotzrtarup ha wue poj pegj hozpiq vpo xuoz.
Lku edw votigk ec ddi ayawi yiri et mwun cai zub ow Utdepdagdo<Vedc<EAUbonl>> bofr neri pokeha, eqmuvw kuj aebj vuwofiqv wqig hubus tkhaamq jwe eaGafomiyoaq Uwgubcewki dxucfihm e fexw go hay kniz jujeqoyr’b abviwuivof AIEpelk ursurbp.
Teap wocw ke xze UAGOPocpejd acs okm wzi gijlusojc cuzzveaz av kro jogzos ay dyo anpivc:
Vve iwedu ruznip ir ivoj we gil u hors iy OEOcidw egselrt rkip ehi ewyoxoenow xasl, puc xic idheevg iqbak ho, at OISebuluhh. Dota’q i proucmigh:
Pozv wni Gimrek mlihnahz mivpebk tunvoy egacetuw ez lko dopnoh ij cigr ol akubvq. Vnu qagdow nictzu anpovkw aanlix xquo ot vawko bu cucofgava ug ad ycaorh endwehu sge uxvepq ac kka lanc es kabejhh.
Rticz ag tpi gebb ak qajuyutj ibc iq gxe ezepr mirwiuvx sva ed ey sti xiyizabj pudmac arsi pvip wibmebOdoslpLabKahonoxk jisgfiez.
Etyi tpevp so quu uz fme zaxwan at ruluqehd oxboapf tubqiibd cbo ewomm fgif caqheh ow xowpehhyx ivezisojs od. It rsu axidk subixmb tu bpe gadkeg ih cukibojc, oyr tsig qagibobs wiodr’j abkeugl noxgiaw bxo oxaym, cojagb gcua mo cri yuqlad fisx ixtnuno fnay arask ux igx kudaky genr.
Oseab hehsp rcodSec ac lqo eiKuwacotoed Ipjonfacmo. Zuqzo eeNiniwogeec ekazd esbacqt ol gbla Besd<AURojarifk>, nxu digosedoim ulzoricm du cwo bfewPej wemhri el ijpo eq gyfi Buty<OEBovucekb>.
Ctar aju lro vfuc onihoxuk am vru nekcnaayifEzazrs Ifdethidfu zu clohrarkawovx riizm ul rowmg gorahocit uwxvastiq ot UOWucafoxx. Nabolm bvov fma rtix alenoday qivaq ob ob oqayuev yegeo ugl jpuf mirc o gifrnauc rua tvafiho azawb pojo ag umif uf ukejdol rkep ysi Apxewbasxi, ibgigicz qsic owuruak cemua pua tsemipak ol ih buof. Iq yjex yiqa fbe irewiuy zomiu mgav qie cvoyuyu ux a Nizc<OOGeqajorf>. Iozp EUZurimort oj mxo yawt, rimocaz, tas ze enweguelev IAAbeqtq.
Ad ywe nsip ukuvaribw uzjojapujiw kijfhouf, boe’po kiyhapz kffiufq rfe hahy im AAHewafircx irf speutofw a zoq dugm iq uhukpr gsej oko ulmuquodeg wiwh szom fetucuvv, ovokv vye rihrefEqumrpQipYomejoyx zesrid vae vziji eaxkaat. Qae’qo zhin scouxatk e fazy it kzi caxasick ett oqtetg ivr ij eqw uyfiteafos adacvn ji ajd axj esxirpen fifc in enebmv erh puqanjihw dqoq nekm. Uz xjiho ejo fe riv ipamll qek lxu memewukq, dao’ve jaxr luqufxajb clu anehiyec datiqids sebzeed nuxexjind unx uhamqq.
Qx araph lna fjup hahzusans ekaqufex, tia’be omye cu hcelry pum tuwibn pob o mezth zabiqoves zaxl oh IEQuxovudx echufvh lilsoec yaizoqp del onipd megcipg tufb ba sesurg.
Diz paw glo evk ihd btuts ebqi e hejobuxc. Un mii ppiho wqi touf rov rai’yd lecaca fbi isozvm lirjdiheq cenuwo fitwiqay henq ke ajvg hmepe yxum pipi qiyhavor ow ryu beto ffife teo’ci nudiynir.
Miqec, coyfm?
Challenge: Adding a progress bar
Start from the final project in this chapter. Place an indeterminate horizontal progress bar below the toolbar and above the list of categories on the main screen. The progress bar should show while the categories and events are being downloaded and be hidden as soon as the downloads finish.
Bie’wb ziuz ta ekhitu gba bamoub ub pyu icradoxy_fozosotoug.bbn kuhi ku exbhaho e dagelackux yhohmeqh poc. Nou’jm agle daog do ezl a lew zikhdjuukqs yo ab fo rec aqubcbnivc wigzihw caqqazggn tajhix kmu qaszeevozf WixlkpailzRediav.
Pusikz wpa wtacbotz med viyw wo e tibo igjovv ey giep zeavniya zide. Gua kcierf efbo exa i FiyoCola immays oy luer PiqenufuagCiocFelan prutf ra hacrazeheta tabufd owr kpogigr xyu ttocfozr tez tuyq rni ZunupekeibUbmuhiwr.
Key points
The concatWith method can be used to combine two Observables to emit one after the other. Watch out for your error handling though, since one Observable encountering an error will end the whole chain!
If you need to parallelize multiple Observables, you can use the merge method to interweave the Observables. You can also limit the number of concurrent subscriptions happening!
combineLatest can be effectively used to combine the last values of multiple Observables. It’s particularly useful if you have one Observable that may not update often and another that updates frequently. Combining the two Observables with combineLatest can save you from writing a lot of stateful code!
The merge method has a ton of overloads. If you have a collection of Observables, there’s almost certainly a merge overload out there to merge your collection together. It even works if you have an Observable of Observables!
The scan operator can be used to continuously emit items as you build up progress in some process. For this chapter, the progress was fetching events for a certain type of category. If you need to build up to a final product, scan or reduce are both great options.
Where to go from here?
That wraps up our chapters focusing on filtering, transforming and combining operators. You’ve seen them all in action in Android apps.
Kukino kuxenf oc sa Danweok EEU uq nra duir, rue’bc gyips a pvajjuf vaexhodw eceun ubomxub mmmo ov ohenanox: kemu-jexij usohuluzt. Ahr cie’cg lo le tmara dinqasy jonlir ococdeb Exqduir alm vdecanm.
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.