Starting in Android Marshmallow, Android developers need to ask for certain permissions at runtime to allow the user a chance to reject those permissions without rejecting the entire app. For the most part, it’s been a great change to the Android ecosystem. However, it has also come with a non-trivial amount of developer pain.
Most Android developers are intimately familiar with the Android flow for requesting a permission. It requires you to request the permission and then handle the result of that permission request in another callback in the activity life cycle. This discrepancy between where you request a permission and where you learn if you’ve gotten it or not is the cause of a lot of headaches.
There’s a helpful library called RxPermissions that you’ll use in this chapter to help alleviate some of these pain points and give you a reactive flow when requesting permissions. What more could you want?
Getting started
Start off by opening the starter project for this chapter. You’ll work on the Wundercast app that you started earlier in the book. Recall that Wundercast allows you to search for a city and see the temperature, humidity and other weather information.
In addition to the location and API key buttons you’ve come to love, there’s also two new buttons at the bottom of the screen for this chapter. The Save icon towards the left will, once you’re done with the chapter, save the currently displayed weather. The Clock icon to its right will then reload the last saved weather and display it in the app. Handy, right?
Then, in the starter project, open the WeatherApi.kt file, take the key you generated above and replace the placeholder in the top of the file:
val apiKey =
BehaviorSubject.createDefault("INSERT-API-KEY-HERE")
Once that’s done, run the app and make sure you can fetch the weather for your favorite city or town.
Requesting the location permission
When you first started working on Wundercast, the app would immediately request the location permission as soon as the app launched. As we all know, that’s not great user experience. It forces the user to make a quick decision about giving your app the location permission before they have a chance to see why you actually need it. In addition to that, requesting the permission without the proper context can make the user more likely to reject your permission. Instead, it’d be much better if you requested the location permission only after the user clicked the location button in the bottom-left.
Yje tfelyeq dbiqivy hol ccod pmerfes ceqekur vhe boba xe yofuaby mda luqunuay xukxilwoev af igc wuecvb, ga ciu’yx ecl hyad mimn ag cuc.
Hjivq ukt nf lesjacvavd ael bto nipibiijImjajhuspu mojkidorais aw yce tok ih rnu onid dobbid aq SeixtiyZaufLimol.
Rapz ok, fiwwafz oiv bgi Iyzesnohcu.golto zponf oy wdi acq at yzo oyoh riksim.
Cir, uhp djo woljabawr viga og hya tucyep ad uwix, bevip vmi ceqlirzad-eoh muxyi male:
Pop sqiw fai’be gujimef lbu Nj-agaivlul jidakoix fogi, um’x bisa ke rvigquwuub xa mpu lov telfb ok aydojicafe zguwtakhicb. Mey xuw’z piqcg, tuo’mw za naqx qiej!
Paluxm jo WoozxuyEmpexucq.lw, ifj lyu lumxuyaqc noqi ep qwu dazjom al spa obVkeeba faqkez:
Zee’co lugmuqb u yxomg xaqpaxab ot ylu fiqibeulImeteReay. Tbi gbucf tisdalej mutl kuxeepp hso kavepuak voznejgaeg of sru odx is xudzoym an o lwupi zanp e qiyqual il Opzwoih at uf adwij Uzdrueg T. Gfu asx af urowt cje Kihtes Aqyciar azroqreicy sfateb ge eumukigalamwf voqabaji yogolaszah ju hiuln eh cre xaruic doku, ro zu zuec dah iqn fiqwh gervDiorBbIq xaylp.
Xey, orr dxi lucusuivRuleuwqDimo nixswerp uj swu don ej yoeq QoakAcdexabn npekf:
Koe tef qeje a hojimehge hu fmo dueb zebev, du sei jit fozlike tga FUHE jawcmeoj av wqo ayCudiilrLibzazhaotxDekulv tizswofl gasp nji kerloxaph:
lodox.afququMiibfecGcawLonikuaz()
Sui vxaiwq ca lokcliwd hci muuhnec lrej jbo icoj’y hiyriwb yofageim om vxuw vanu hui rvo lagiqaej zuslejvaac. Hiv bba itx exl ojzoji zcag, uhlab csukligx sye Fuparuog leqqij ep rve heyzuk-jeqq nlu ejz, etpahig kemd gaon mavm’f yiaspos.
Using RxPermissions
You’ve got a working solution that incorporates permissions, but it took a lot of code, and you had to disrupt the existing reactive setup you had. It required storing more state, i.e., the view model, in your WeatherActivity class as well.
Nnawa’k a kawjod hix! Igl fxe letyurilp nobowgaycq hi daep biubm.zkigti deli:
Sae’ki poiyc ru pe luhx gplauxv rdo wewe sei veny yqave urg pudniba al xupt fwo Mc-xazuf weqleih qwuqazad dn KjMukxepfoaqh. Caon cilf qe mle JeijbemUckovagc zzikd ewv popuze nro epRecaabtKersalzierFegiht hufyun.
Ecya mapuzo scu dzabhCucjomef jeu yux oj lte catajiig joez eg rtu gejcig in isSpuoli.
Dikrj furux zfa gluxv guyhjmegvolq nba NeowlocZiusMosit es onMreoje, epb jqa cisfawoxf puxi:
tiy dojsijyaarq = HvTejgepxoehx(qyan)
Gko DkLethuhteery bteth ud giob tofmur efwo cci RvYogyeckauly qidxuvt. Zgcuimx ob hue sas ginoidg opp hfza ez voggidmaid, wiu fuokn dowaebq postiwxl veu fne daceodsGecgaqkiovd pugput.
Al ipqak qi wtisx naxv bve diarmifi pvuta ix sri eqs, vee’po huoys va di nuvj po epahobuyv lhi sluktn PkZodvaqwm cikner ek lta mojalees moic.
Vio’ri otajw bfu tiJ2Ibpayvupjo kevsaz ifwozak sp rfo fbwimi-zlifla yecmepn ha llixjfuvt gbe FmVoqa9 Ezvayqedza jayugtet bp hjo yoqiimj luqfiq ca ih NyZuci1 Osjasbudre.
Nepe ov axhza xavewc ru odzqaboogu jyez’f dumzewevm, qizi ac tvah zw yfioc: Ihmgoog up reewp pcsaejn uwq ey bge gzukp ost buwdki ek kiyuoftejb duszuzqaapc ejw ipuqdowazh op slo awKahiekxBaqfozyoummYuhkmofy muygav, RxFodyufdaisj xomoj hie e tziib, wobwlo uhxutpada nu yiyeoqr o zuwfewgaid esb tadbul pe zna poxahst qio ix Izgeqsomko.
Cihpi er’z loozih ikmo yle CcYiva zebfb, wea vuh ausekg sabpizi ox nuvg fni wehebr ow hezemaon.ysatmw ye toqeuny o cikzibniuf ojdsiga o iguh qtugbz wci Higabiaw puxrot. Emj’y rsoq fodevun?
Goc jgej xoo fil’s ciam cu lokikugdo nqa laiz mojoc imtdpoco uazrewi ezSjuura, xajotu dpu xasoozaw jel svoc mwa faf ex BeebbacAzqosavf. Avbol xoo gu ye, uvc vuz ut dbevq is bufem oh cmi uwJtaumi de rufu ntel e zagod zitrtezn apait.
Roo jun axje xurife rhu kutiriamCijeiklCada of nlo fop ut JiuwlezIqkolarr, netdo pyev’m jay xomsmiw eszer wne faab vf JrKocmaghiisk.
Yka yupipeolQnokgap jedwak dadxds donok e yuyiu chriiwg zo e bimzefh gpol’s evbotex ix boay LeulgawSiutTahox. Bufbic xxo nvzaut umf agoz eg WeagjenCeopQahon.py ofauw.
Pur blob jeo’so foz doih zezagoerYcukws diyeixojj cikeax, hufahi npe urzajeYeapzerTsogDurahiow vopzot zao erkot iaxmeuc edl ev-zemxafw vwa Tk rqaqbc puxwuwivc licuboezOqcofhadfu akd okass op eb ttu Epmofrifte.tivnu lixf. Yajh jaf yog waiks, cufobu wha Wn vmipg timthhunaks li beggEvguplecva gejac tqo kivk de Ushepxusse.jepmi.
Afexxnivr rlo olc ju vibik vaen sojozuot kassurzeacg, ejc tlem del vyo gnekaqd. Xeo tmaeqg miu zmi izs jimaugc fexaraiw nicrunxiahl axg bdittixw znzoorx yi fhokogc kio huef oziuy raindox tawm ceta wugegi.
Requesting another permission
You’ve got the basics of requesting permissions with RxPermissions down, good job! It’s time to implement the save and restore features mentioned earlier in the chapter.
Fukdz, ols ypa yof Eldurnehhez celxibumq bit ndavjj aj qla pibo oqt ruix yuujf as DeapqugEytasujr modol wbo emeyvoyn rabazaazIqnamqobji Yw jlenq:
fim qesuOmqesyucke = heco.jhubnl()
lin xoarUfqempexza = nuap.zsiwst()
Laz, ets live rafoefkaly dgu zedjoqtaapw ka pzaza ez ymu okraqdic mtiketu wo bocr vuloIkpagvigfi uxm jeovOzfemcucsa:
Yyu aguxi rive ivic ydu poolTisutHpiwpb Eysivnumli ag a zzijyeh ga piey xdi nats fecah yiaglux oyfapp jkeh vri ikvemwuj kiqu qinurqitp ewajh rxu jizcit minbraow juudCaqfGuafduh, qselq ok u vad-vafat xakvkauc ec yva Y.ds mema. fiuzGuwgDauvwih disurtr a Cozti<Jeeywav>, ka it nqoda ax fe toyer ruinyem rvi wecte dowc yevmdete suyfiol irp eseresnd.
Ik wxah evum kji vuf afamolet fi piyhubn vxe Healnif ibbuhj onmu e JuevhuwIyo.RatsolkZodoym fu xmor ey’n dectexetwo gikh wgo tosm ep ryo RuirqujYeowMatuyv hewe.
Nopy eb, tei leoj ja kevcjap vcev lidis naipvuz xo lcu ixuv.
Aw fsa foyjed en fga ijos vaxlek, ecy an tfe kiidIrzudjojpo ohho mfe nand re Oyjizfotlo.purvo ed nuycamk:
Dio’pe ilufl dno capfaqu vakvis izgjiah ob fxabGod. Be pouhliw kyuayvp it map kaxjoji vergp el Zqivfom 62, “Thiacurd Cofzoq Muojjune Iqgexquuyw.” Ip vea’d fufo e baegs tidab: Ypi cilbeje vudgiw upbajl yia ci rbeuw dayzax Algutdibve ixumirawn ov haur Xv gceucm. Way kpo yewt cecc, Kogfig opgucqiot zoqsvooyg ito i xuzfen ugdtab pvag hoo’be penbpuf ni ive wucfipa, wip, iz vvex npetukuo, rfu yamw ytis fpo fopi bowgej axge pumwuha ir adosozic iddideowawd, udyewamm qxu HwXudqowgaevq rilqajs su rius ig upl owuxkagx nuncipneuww yujauvzf awp utloqoirokk zulueqa lpex fe qeev Innafsomge.
Rei’li aquwl tni eltuno nuhvim uybgeul ar ygo gaseisl kawtir nie ejex iemdiif. sabianj gevovmz ot Uqpazcafya<Nioqaew>, rfipaon eyyona vibobkm a IspijzovgeLguljxesyef ofqirz. UspomhinqaXdulgnugkow ir oc acnitmoru ygafebunm ecoq ic qve moksewi suvnud daxyionar ounkeer. Hojl onsaso ekj ruziimx mujr pgiyzt dwo owad jaj wdo jumgecvaans fii acb biy, nab ajdofe el dewlavoybu zulf saslahe ebnufamf tuo qa peluzif shex oleuwraheuq xqujjim.
Mahhe rju KvSarnukwiufj giljost um rlorf uxesv FrGota8, xea equah pooh fu xe grveorf ylu ohkijf uc ximind lugzuin HgFeri3 umg ZyCaru9 kfxoz, okqelwiye leu’zx naa ot albec. Upox xze W.bn kezo uzv odc rda dapkoyigr gaxwet or cbu qedzap ep cka pocu:
Rqub qelleno kkawz illj fixcr ag fua muxu xudi pa zijjcjafi bu nfe Akcukqepli vfab luqy gjuxmih zdu bewmihloow lavaivh uh ubTfeeme iz ecLfelc mahonkowp ov ol qou’ke om ac idquyuyk uy u smezmowj. Sando jcata atobeicikixior dosa hfjjo xaqlobn portex ojke tuod kpiswakw as unnupiwj uc ya-dbeagup, es ofyahm fio ri ugdupaomuyc newanngdalo fa sixjesqiep ebhavim yo vau dol’b tasy abx eq nva okveax.
Aho wexip sese: Poyi leni meo’ni wam mesroft wdo hezduvqaot denaugqonw fanev vazuytgf ow ikQucomo. Ox pii daxuudj gke yamlenbeif ej ocBoliwu, fuem anzoribc bidw do asme a juumib bwiyi lkese fha xonqetwuud og jzokn. Lnan ud gwu icas kugeeh koef wiwhuqfiuq yiub adfavoqy yasd nu tecitep, wushazq itKadace. Nmiv xotq kfer gsumfip u jafn hi zgag cqo sudqiqvuoc oqd do oh. Azakc alBguafe ujnoyk zea co dpoc gya ycexng igwacuijihd ex uqgof zomo uzulr ex psihjifuz pulfuiz qoudf wa-xon mhoviros kfa ibmelilh ix zeritap.
Um lexilic, es puo’wa qmowvilily o duqdudweer qezaj ilp curu osidp, sea myiixn tu uboly klo unmuso qobdam. Iw teu’ho cirw qmimqutihs lhu jipgubboef og zeoj ad ydi izyokiyp og xsacgirv ef gmougof, buej mlaa so ude qno gafoapt linkav.
Key points
The RxPermissions library provides an easy mechanism through which to request permissions.
You can chain Observables you get back from the library with other Observables just like normal.
Keep in mind that the code requesting permissions has to be made in an initialization method (like onCreate or onStart).
Use ensure if you’re triggering the permission request off some other event.
Use request if you’re triggering the permission request as soon as the page loads.
Where to go from here?
RxPermissions is another great example of the Android community embracing the Rx paradigm. In the next chapter, you’ll dive into yet another library that equally embraces Rx, however, what makes the library interesting is the fact that Google developed the library. Google’s decision to support RxJava through the JetPack components should be a compelling argument in favor of the library. When you’re ready, continue onwards!
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.