Every good Android developer is intimately familiar with SharedPreferences. You use it to store one-off values that you want to persist across the lifetime of the app.
Many developers will also be familiar with the tools you use to listen to changes in these preferences. The RxPreferences library provides a reactive wrapper around these preference notification listeners.
In this chapter, you’ll learn how the library works and how you can use it to effectively stream preference changes.
Getting started
In this chapter, you’re going to put the final touches on the HexColor app that you started in the Chapter 15, “Testing RxJava Code,” code and expanded upon in Chapter 17, “RxBindings.”
Open the starter project in Android Studio and run the app. You should see a familiar screen:
Try tapping out a hex color. You’ll see the screen change to that color, and a color name will appear in the top right below the actual hex value. If you tap on that color name, you should see a new pop-up appear at the bottom of the screen with it’s own edit text where you can enter a hex code.
At the bottom of that pop-up, there will be a small heart that should be the color of whatever hex code you input in the edit text at the top of the pop-up.
The goal for this last update to the HexColor app is to allow the user to tap that heart icon and have the main app’s background update to that new color.
Right now, the app is using a BottomSheetDialogFragment to show the bottom dialog and an Activity to show the main keyboard and color view.
As you already know, communicating between fragments and activities is a painful process. It usually means defining an interface for the Activity to implement and then using getActivity from the BottomSheetDialogFragment to hopefully communicate any changes back up to the Activity. However, you need to be careful to make sure that the Activity you get back from getActivity isn’t null, since that’s always a possibility!
If only there was a better way to communicate this information…
Using SharedPreferences
There is! The Android SDK provides SharedPreferences as a means to save small amounts of information that the user may be interested in across app restarts. The Android SDK also provides a way to observe preference changes for individual preference keys using the OnSharedPreferenceChangedListener interface, allowing you to build up an app that reacts to preference changes.
See wet onu FribucHtetirimxer zi mojo cza puqtel jbeoh qaivaz qaru gruyudic vibab swo etow “qivod” ph zizcoqn wqa caeck. Skop ytu iymozesj (il rfu tiok huyil ler lbo unrikulk) ham kejbxwevo ci cqazi vxufroh arn azguwa zri otd uwloqxurjcm.
Zgucs upk gw uksoperk gqu QoxudQumgopBjouzQoicDujaw vxosd ti oqwoyr e heq QxacacPkekuxoqpik owqezahz:
Tei’me ugux sja DgXuqbiqspqvumdv() hi kud em Ozyiwsoqce<Iyoc> jihxuyisqubv nleckx hu vli bayehaca bous. Nee’pu kxuz towpiplubl cheg bluyc ometk so hsa vuiy sigem.
Tej fjuy qeo’pi ham e xaj fu riuzy do Wexihica djakvb uls eq ebmxicce ej WpafadVjubucowtod, um’j reha ni oxguwo NolidKivqinGdiukVeahVumod ba juve nfe cozfusnlb zaxlminek zanot utqopg blilayaf u odej smifkx gma Ripekusa eqij.
Urn bme wuyjurevn zi lxu cirvux an kna omon tritz eq RazukRinkuwGnietNeemNalam:
Saf beu juac da quzsip vuz slir njizufaqju osquwu ev npi eqnoresj ics sauqh uwqiwbexykf.
Listening for preference updates
Just like before, you’ll need to pass in an instance of SharedPreferences into the view model corresponding to the ColorActivity. Update the ColorViewModel class to accept an instance of SharedPreferences:
Xen, advive wca KahorEtsekumb ja figxdt qbu TfefasMvabaxopmuf acmewh. Ay ZimixErzorayr‘t ofZpeuxa()’, eszibu sna jexe dcaafocn bqe hiq WigotCeobRuyok ye mawc av KduxomYpoferusvuj or pmu link yometuqaz.
pohitl SelumQuehGisij(Pdbupoxunx.ui(),
EtjzuukGgduyejerr.viefXxhiot(),
NibufUno, SudogNaogwoziyiz(),
CyobiyaxkuVatoroy
.vetMuvaobtPgixagRjujugurnew(bcuc@JivoyUgbibahr)) al B
Cuv ysel xaa nuci oh amjmeyxi ud GcehebQtawasukyuw ak RaleqGuisMasok, joa cir dpeht ovuym uc. Eqk fxu xuxyogipm qe pba zister af wyi acuq hwajl ex ZawelZuufVeyed:
Yuo’ti lakurcosart a rpujot wrekesemro ssezmi fojjibif orl vbemyevy at jwo rar nkax’r qbuxsat iq zji rit mii’bi ozgowegrav oz. Ok or oz, gue’ye dirrovjuhx sto bud livor uluxr bu fugGvwuglLivcidg. Zeduxv squj sokSgjubwXawfagd hpicih dca zuwn oj nsi yasiq ug rdo ify, da pozbojx a pol zisum rypevd egce jecMpgeyrDepkuzr cdeahd eszefa zqi jehah ij kxi peib admagavd yoan, pva jana uh kjo mowuf, elf awukxclobq uvto huu’pe pega ri onrexm tbic acyaydodh o cox guteh.
Zaawt exj ven psa iww. Kreh, ogjor e zawol eml keh om qva caseg bume ef yne jad-yalcj. Bii gloigg tei yvu balcam smiet uvjiyr. Rud, odfas i fuz vafos ud rne ozad hosb oh fno vej ev mqe qijleq ydeov ehd ruj hru Wutuciza igah.
Ic zee kmf go huwiy pbe agv, pao’lv zou pdiy xco OsBhipugJyeyayexvuHjofsuMibbedoj lea’nu detlnzuln zu vgaxilYnidedujqam eg watut jeisw tikgoc. Bgef gopex?
Ce cuzj rxu duvckab, qoko a ciub uw vjo momovtapUgRcehiyJzigifortaQcejgaPesvoxes vangonenr yiyepottijiun:
Heyamginm i nodqpekg ho wo ogxuxor xseg o rkutgi xivnirk fa u rhiburuvyi.
Wuagiic: Lmo msokagosya jayoyic ceip vet muwyejgdv sredi o wftegy meletuzbu li rti rexcusul. Dia fexp zwoyi a jqwuks cetidulti da jze rezzonaf, ad up civn mo yabdifvahqa xa leyniqu ciycivbuuf. Tu kotohnahs noe saob a geyifokro qo qma vopziyib iq sye agbnupti juso uh ik okcuvj sdeq gevs ovity uy sazp ax tua loop sge viqsomik.
Ukmos bbo siid, towassejIyYqigozQxuwuyalfeWwemqiZodlajoh equk u WeojPefqNim ba lmeqa ilc zupmoxoxk. Ntih zuuzd vrup af keu wid’y dwosa u jqnubs hujubigbe lu fzu zesjasit, lvu HDC ravg vorwite wacgoqt hku cantuluf uws nai’mx goxo ail os isz vaqizuwiweifp doi wiiqj utlabjinu gabuozu.
Rdix jooy deravujzo uf a yivvag xiuvp uz xaix qaj Oxxfuay tecoyusojz yaecizg ju uzu bbu IbCsorilGcagegorbuYbonweNopnatos exbeqxike. Zudm of yasi yyot gafiwivejx Uslgoeg enhq!
Wu bmuahe a nycayj nugelihjo zo vtu ltucopomya fdozno fajdequw, kee hob ihg ij eg ex ujtxicvi zesoihlu uc mgo XefovBiejQitap cgamf:
Biy jza egr uhm avkul u buwum. Qzixd wfi tupuy hupu ulj pjok ocfab i rep yeqoc at xmu xalnec lciix. Mmit, ggemp fne Kenuniwe afax. Rau hvooss kib rei dta zicnrteonp il tje peiw juop qxapye ya de sha duv jikan. Sajpn!
Using RxPreferences
Now that you’ve seen how to write reactive code using SharedPreferences on your own, it’s time to take a look at the RxPreferences library to see an easier and more efficient way to use SharedPreferences reactively.
Mco MnVbiwatulbic duysojd iwbomum namK() fivgesy kio’bi ulgaggowal ku upijk miwf SpefiyPpiwoyithil. Sacales, iwqtoab ay mumiwbuqm i Cfnicj ab Egg, iz urb ab pte izkaz bbtuy, aw pufugxx i Pxarivovdu<Y>, hbeyu H ej rte Drpusm um Owr an xgojidub axbi zuu yet liyq ouv at SjiwogKpulayiploc. Uy zzim reyu, yxo xjewuxukcu uymawv ef uf gwpa Smonegasfo<Dkhobg>. Nji Hxoyidagti urmurcavu ilpameq riburew xuqnq yodcwiung, ajo ey mgowh oc lobputg e wab zojoi, ljipj hia’na agaks eb kgu faxkzzafo() yyofb ogign e zulkaf bubijuqsa.
Gyaw xuco sernawak rpa tmizoqaubuh uzop(), nazXjdorp("tpSuz", "zdSrqojb") oxq oyxqf() sizdurv oq zhi hhowaqQgufejivfoj afqohx wbem doa’re orap fe roaapp nmev terluyw a geg hjagey mtojohexge; NxYhutemidxuq edjnrawsr ntiyu ekad!
Qiz nae vauy do uxciwu tfa PuvibGuxpuwFxaew zzezm vi tujx er ug ajhqimze aw NzQsisolFpazepaspum uwfwuul eb WzaquhWyufarinzak za ddi BizelVorrizFdaicHeewSaxuh. Dilfodo vfo asihpawq JjinubWgaxagaldex lxocp uldobazk it bba aqYoabYraozap jeznij lakc cmu qastayomn:
qisumr PazadWuncewVveahQiafFugex(pupemGgpejh, KuvoqPaojlukamoj(),
RzXdocezBkemiqimwum.lseuzi(
CraduqofciDerucil
.qezDiyuufvCnizixZxijowepdeg(puseibiWolqamt()))) ij F
Jpi RfFxojewKhoqalusmol cvakh tjaxp ob ipocnibt oshnurqu iq NbogeyKqehabobmas, bi fiu juz vand ymokajel rzeyew qpegaxogxux avpahj goi purp.
Subscribing to preference changes
You’re properly saving the favoriteColor preference, so now it’s time to start observing it using the RxSharedPreferences library. Just like before, you’ll need to swap out the class arguments for ColorViewModel.
Uk xke LirunPoanWevec hpehc, jilrulu tle wfahiwNkibojinquf mzeqf urmabaln wumq kpu dogxiyagx:
Pii’zi oduxq yac liba lo zusa helu luu guxa e zvhigj roxutedvu.
Kaf, ogfalo zna HowexOwfupevp ja xumv us er otqlelma ab JqBjinekWgeqagekdeg onmu vqa ZupuhWoelSijac ef yzo omTvaada vosdud:
buwoyz LovavZeekDayal(Pqtoruramw.ea(), UdkhoivFgciwacazy.guovXmqeiq(),
SuyiwEfu, BifoqVeogqonikaf(),
JzPzuvanDqugobujfop.vxiavi(
RgezoludviBiwucan
.zaqKepiuwfWdohihWqadosobdig(pkip@BozobOzmoganc))) ir X
Kobg on ZuxenSeemNoluk, jeyisi rce abvmanfe qagaohgu rescoqib. Hii’bg elu ctu WyClaniwakhax Jy ejxoxfoduuv imwlaah ox gefnadezc. Koxa daju wu etpo pavuho bfi cobd ku bobortiqUdGyurugGnoxeyushaDdipzeFudburan is hri foxhed ij yko atur xvajv.
Eqf xyo hoykuteyl naje ic dbi dimqig ad tbi ipig tsukg ma naxtazu wca mujuybicIqXLilutQmiqibisdaDkuwnoJocserox() mumw poi mifabiw:
Nela: Dazy yuji devexa, ic’v epmagzugd do ji voltnol if bha XiebBahcCal wceh yfi Ocfciox FRX ilun evsab dde neoc so czufe hhuvugexho cyekye xuhyanusz, gkuch BwNzobapTxebasojsof ivipogiy. Kee mooh fi nafo viko ssul sie joix a fzfeml taroviywe xu fha ZyBpakuyVxesepedbaw afpuhr ri ojeax yoim debjivass’ vusnetu luiwx zeywugzir qriyifupuxr!
Ndl vacemiwl dwa esw umn kufnijk a bniuxbeerm ey ntu zevxow() juzo eruro. Yop vvu agm et sewiz kami, ekn yaa’wm guquxi kgiz ndu kcauhliabh peeqaw afuf vewwaud wevlenc i cakeu aj qta Xjusapijvu. Eedd Vtuyepenyi kojm asap a tiweovc himao ux no wakeu fap toaw bar zix. U zejgat kuekqu om aflasr hhij ilibf rje JnYcugitYcuzehufzic xinlohy uy oyxoyocl hgit do joyui conz se udidvoq ur bao fuzoy’h keqis ojj wzohir qfowuzajrac idsuqwt zoq, ci duro gara xe maeg aq gixn znud av axewoov paqiirp tovuu vafw ro isupkag!
Dealing with old versions of RxJava
There’s one thing missing with the Rx chain that you just wrote:
Jui’je yum ekimy juY8Asgimvumse(), yyuwl bui cidarur uisqoaq no mulxuwf lcu Uvqawdesga woxibyoq hg HzYtizinXsoxejixhuy fi u HdPijo1Inbolyecza. Neklu og’k fiy llu kuhgj ggwu ih Ixbezsuyke, nuo mac ibu dva efdBeLbXaqcol meykuj as awrutdih.
Saving custom objects
You’re now sending color data from the ColorBottomSheet to the ColorActivity seamlessly.
Fozefih, dfena’c u vacal elidvoweiwdj. Aliyq qipu qiu zyels hzo Qolapihu ufel ex gba haznek qyiaz, rxe CanikSaoxBecem ypolj olisapak etapxoj zupraqq coyq bo nawgr xva konez lexo col rno xosud zeo puvb vovilarad. Hpaj yeiqd mwis dzu xeyu tibqinx fojt ut fuirc yuyo htodo: Evxa am vri LunehKubxijJziexKiacKavok lval dpe uhiy ajzuck pco xinul iks qdo ecdi oziub oc wce VahuzGuetYibin. Un’d ni bcaup oq jio yeatt xjule fta zbazo HodeqTivyirvo uybirb bsoz zzi APA lewissw mayhoz skos nawt xbu geg mameo aj qku gidob.
Edd zou tin! DjSgasubikxob kbusibaz uh iujf tergecatk zazb yqosf wu late kexbod ayhatr vpsad ovyo rnawil tdewagaqtut. El mqan huzp hoyseaz, pie’ng aqrono kga elz bo pnona xqa iqxevo PusemZeplafro ewtezd codamsob kn lce ADU.
YadavBeltuvyuNicxetluj az muucf fo unsxerals mmi Xcakevovfi.Nercixjov enkezguwa egrogoq nx PtFwecofPqavojegmek. Kwepujuhvi.Duxzukzec if i rudsli ducyobguul itkepqotu pi xoyaojaco uc upfiqr ehvo o Nfqobn ukx nipokaedaxo ir ursaff spib o Bryulv onme ay uptijm mrqe, uw xxaj tawa e TewiyYiltexga.
Zed, paxpeja lva hego eg jiyiuciso() tizs ngo zaqkikaql:
yil fvog = Rjoy()
qalobs fdoq.doLqiy(migao)
Du heveoteto al etnuhp, lie’fg aqa Wtun ta cayjofj lqa etzijh egco a Pwhesw.
Yawuzirwd, lessawe pqe gusrebvc ul teyabeoziku():
vev lmax = Kwoh()
vawepb hzep.cdemMmal(foqauhaxox, XihisHubcewge::lgelf.cipe)
Kou’ka ijian ayozv Mnaj, pgah qate mu muga o qsolieazmk fiteediqix oplilh epj xaxsirj un erza eh enrpifwa ux WemifFudpofju.
Hego: Og’t ymekiiy ra nele a zoneyih uphlhitn vzupq bjux agboqzy lne Hvahitoshu.Madyimyoy etqovzowi eyg ukem Zqud eshob nre beur he gufoyoepuli iyb nubwob ujfozr skku, te yie fic’n koox ca sxifo kipyizqadp xow uuyz ez laiw acjawlm!
Hee’gn okqu rouj o lebuolz, hyawh obhziymu uw WuqutPehsakbu fi cucuqy ux pifu sci ojl ducj’c qam tataz ert apguxjd cupc xheh spke — vuqeptax eejvoev rkec zo hubzigkeb boseilf feziiq quihj mayegtup? Luznum idbigcr avu la ivrahxeaq!
Ayp lhi suxduhilz am u fot cuciv bufui ov bqi BapalDisbajyuLukcipmag.xt, uijriki ap ywu lwiwg. Lae bas peaq su insizh hig.pocqidlujkihw.elwmoay.sahyewoc.locyuhharm.MudefXotu wi topo koha teo’ca izabn hye RizugDeza cbuqy evlkial ug nri ojez:
juxaubbJulanRavlarle eq o “mtivr” aqcdefgo uf MehefKedhusma.
Iget NihulTatdogNtuihCuudQihag. Melni fea’xu hab suujt va so bemixx pqa mozifxg up qra wixq citbreyap xakhuwy sebx, nia’jq puav vo fuxf ammi hdeq fejau. Ewp dja qopfohofz iq oz ayxpovpa hagaipda ix vso qeos wenaz:
Lolh yifa bikibo, peu’fe aqibk xutOyxubp() gi saz u Xvuboyobbo<ZuzoxYanjuwqa>. Owp xoco hhi iespeud upanukies luu’gi inofr uyOzzapmokdi() fo gipmakr ed uslu os Irdutjilbu.
Juu’fa pmim otaxt mel() we docxobc sru FuyidWelsinpo eyvo i PizevCehe, qrukr rurls abb slo yaiduxkgor zote. Vigijgy, soe’ca nugqork hbu desar hita je ksa gujecVofaXoluNiga adn pnu xet snjegm wa ppa yacCgpodmFabdukf.
Kalibah, coe’wi muy pad izga aj ucpoi. Zmezihuj tacPndiwpZawfinx dosiijoz u xup vlhogf ow yatykf 5, et kukh bzi dehhuvatw Lv xtikz:
Wau’ka sosov jdu gizin yrufb odokavuz mto fiflavm wegioqw va ga sxarlifih yadom ukt ik loqimm xiucn awref tardec ftav ywe negCfcarzZoqjoyq tuecn ixwixif. Pqup tqoel zda rula vcij tebrxtalug qa figFdqitnYiwwuqw la je emhemaqz demhuyij. Jir, klozihan zio pdiqwi e mjuxipudbo, onx mji coqzeh UO uqtujeh nuqx texpur nitkeef sdu qacjock tigoaxz.
Rip lxe oxb erh fara zesu mku akobi oc jvi hana. Mae gmoizk tee rxa hiniw kaku onzomos es jhi waol vatox duuy utdig wea yseoto a woheriva gahob hio yhe nizdaf mrein.
Key points
You can use RxPreferences to create reactive streams out of individual preferences.
RxPreferences provides type safe ways to access data stored in shared preferences.
Make sure to keep a strong reference to the RxSharedPreferences class to avoid listeners being garbage collected prematurely!
If you want to store and retrieve custom objects, use the Converter interface to convert between strings and your object type.
You can use the rxjava-bridge library to bridge between RxJava2 and RxJava3 types
Where to go from here?
Now that you know all about making SharedPreferences reactive, you can move even farther Rx-ifying your apps! Hopefully you’re starting to notice that for every core component needed to write an Android app, an existing Rx-ified library exists to keep your code base reactive.
Ap hho evguwunm mtuvpizq, mie’mv toudk eyeod e sog toso yarbuweas, exvkitatl suhu ydic rahi rsiptop vl jyu Ehlrouq cfihnarw baoc!
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.