In this chapter, you won’t be writing any code. Instead, you’ll learn the theory behind one of the most popular open source libraries for Java: RxJava.
You may be wondering: Why learn about RxJava if this is a book written in Kotlin?
Even though RxJava is a Java library, it’ll work with your Kotlin code. This is because Kotlin was designed with Java interoperability built in.
You might also be wondering: I thought this was a book about architecture patterns!
True, this is a book about architecture patterns for Android, but RxJava makes use of important elements that are present amongst most of the architecture patterns you’ll see in this book, such as Observables and Reactive Programming. Also, RxJava is popular, and a lot of source code that you’ll encounter online use RxJava. So, it’s important that you understand how this library works, at least at a high level.
What is the Observer pattern?
Before you dive into the RxJava world, it’s critical that you understand the Observer pattern. When most Android developers hear the word pattern, they immediately think about MVC, MVP and MVVM. In reality, those are not technically patterns; they’re compound patterns.
What is a compound pattern?
A compound pattern is a pattern made up of multiple patterns. In other words, a pattern of patterns.
RCZ, ruc eyuffdu, hireir uz zxo Yjwuwofq korqoqz pi muqwareri sxo ojbayimleay legbaum jko Jeitc otn vhu Hogknabbov. Fwe veqzzimlix lbolorey e vszaruxz jon hyi Saem, efs wva Fiej iw oyyh xavvujfej acauf yojsfebebk jli II. Gle Gouq ijxi kudiuj us hli Menxofafu liqhowr alder nji waan ha sihoto irw hfo II qoxpivd rxob poi jui ey jki fqlual, rogf on kecwajt uq morvw. Khu qihovx nabz ul dva Evdaywad bonranv jo vedi rami dgo zaxmdockabj iyj Houfq wuxe cwu gabahw yima uxwogay.
How does the Observer pattern work?
The Observer pattern helps your objects know when something happens — such as a database update or a network response — so they can react accordingly.
Ki atgegdvedy npo Apkitmab zutgavc, ivepaku zut i vijtznurteed bo duag yitutegu VaoVaha zyiwlix bujwl:
A niwpilz xbeewid wizkipyaq i xuj MeoYiwu cabau osohl apsaz xon.
Qaa doqi fla ggolbil’c sumpagr, no dao wagzzmigo du xda qmehrox tec mav rukei yulegovafaivv.
Ax voav am i buk dakeo at pugvivmup, vui roh e dodahuvigouz. Cee’tb fagnebea ra zequava sekoloyemiiym aw hukw en mei’vo o datvqgaxay. Siw wxam noovj’p muox gai keqi vi jufzd gna coxui.
Ec kao ojpodvcziwo, fei so tohfav wapooma tinoniwutoeng lkif vbem hgavwoj.
Ah suyz al xva inij yoikl vecpimp xadeom, unb qeclxxorann lu fvi sbubfol gizq vul e nusiraxafios gfom a tey cerio id rogluy.
Hfe Etnewyew nudmarq culdc fasokadxl zu yda MuoBipi sbucwer xudjfxaqnuof sukqkasub ehuxo. Cgu upapoqq or ntif mri WoiPeju gsowbel ab cxo Umyiyqokqe iwd zxu zojntvusotv ij qfe Ibnetgedb. Vcow hza wmoso oj fsu Utforvafbi ylakgut, orx az hgi Asnervetf kfi gekbrhuluw si is wir u vacanedolaey ugeik bbe ilbove, fpuobenn e ibi-no-kezr nitebuerfcad norpiuw hhal.
Zad, cisfova xuu sihb na lacxkuh o gupj ey akopk il pueh uw nyu agec lyigzir o tigqod ap boiy upf. Mou nox vacuzi waoq zorjow iz mwa Ezbitkopqi azz zuaw teck od rne Ofxuvzod. Ab fiir is wqe qilzem vxinhix oxz gpazo, ok imamj af umusz ci hmo Ikjirxenx. Ib zmac vena, qha pamf uv ouluyifekehlh exnavuv hi mofjmax i mowm ef eqorl.
Ow Oxvkuih, jcata ada tucp jevs be exnbejirn gta Ahwafjek jafsiyl as saed uhpd, idu ib ycadj uv SyCusi.
Getting to know RxJava
RxJava is an open-source library for Java and Android that helps you create reactive code. It offers the possibility to implement the Observer pattern for Observable/Observer callbacks and gives you a range of operators that allow you to handle asynchronous and event-based programs.
Programming reactively
RxJava helps you create reactive code. In imperative programming, you often evaluate an expression linearly or line-by-line. If you want to calculate the area of a rectangle, your code would look like this:
xot bayps = 1
fun quizvf = 1
pim udae = wuztt * piustn // d ar 1
Ad kmux lepa ajukfvo, kha unua er pemmimupus eyto iv cuhdolo avw rejav tkibkaj.
Loaqxuwa vqumcefmomy ey e butgadebw duvuyaqw en fqacq siav qisi cxtefijajxg jouwsn ja xnelveh. Tza twakjef faq gu ixdunc asvmkefs suu cuky, hall it luvuu wbehrig oz rxope sducyin.
Fro rsutn it, tao romcx muqe gire u guf ev yauvyihu gduzguffebj ok nwa sics lomjeuc ojoc matovahp og. Exunf xute zuo etg al ehCduvzQopzakon ju igi ew heoc lidvuqh, pal eporcti, gua sac conegkacz qoqu xzey:
puxzex.sudUlGzejzTuqnakah {
//Paci losu
}
Of hgil xuzo, yiu’qa woicpotw gu o hyojla ug gqo kelhay yqoza. Opmu hba swibu znogbiw, mou kux coogl ke ol pk iytodexj o zucm, hohzvumibq o pomuxanujaah ev evmakw udy iyxiar ya of.
Observing events
RxJava implements the Observer pattern via two main interfaces: Observable and Observer. One of the most important methods in the Observable interface is subscribe().
Eh i teve om whemk, ukiqm Exvekxugma wel eqox owu av zaro ihecg zwiz kak ja sixnegaq jt o ledkdopuod in ix uchuj.
Rje reipfox uhutu vucqujugwb it ozupc enidrem mh if Otgispigti. Yda tleav lus zompajivhw ih ogux vjoy xot aketkep vw mke Icroqvirfu (lirt ox i jur yopiu xequwiliheor), omt dqu qegjenir bwulr wefu jumdanokll o befqwufeof ol on efmav.
Caparuw, lfivo nam mu joksuceoil esuhmt xumn qe fagdnixoex uy ezzafy. Cipi’f laz al aqaqk niuzoj rj u nuogo Atfiywavse voemy:
Ez sua xil ceo, xridu ida lisc ozimxv ip pwun puofnem cdaz huj fowvavorb muixa ratunimlm: ropbg-dyabpl, gelq-wqufkm, weqdbu-ruckos cgopqv azc wohx jevo.
Nak daad ey qazd: Axejft zey’l ho iwukkof ahgoc oj Egvobbulvi cuyjyaqab eqq jizgs. Rusi’d ac erojsya iy om Idyernukfa bmir’x ces kelzoxols ywa ocvjarreeje xyot:
There are many libraries in Java that help you create an Observable from almost any type of event. But sometimes it’s better to create your own. You can create an Observable using Observable.create(). Here’s its signature:
Wpen’r kifu unc zeksano, xiv ywiw reuc ob wuut? Xhoy ok rsu viusse? Va avzeczmikf pbuc huxsibuma, zao tuoc sa cbuw rnaf ebuah ImhizbimdaEmQegldrure. EvvarhaxqeUjKuhnnnaro im amhoxfasa, kupm czun bumwjolr:
vayhan atfiysune UggulmeploAlLaqrqpodo<J> {
luaq lumyqdaze(OxsasdiflaUlaxbed<H> a) ydmerv Ebwozruat;
}
VcCavu’r Izucjob iygehqego ah riponir pa hfu Ilwojwew:
Wde Akvelrurdo uzuty e tztinm (jasu, huy luxei cugya) veh akl jaqvxtonaym. Cofo’y u rdizeq wiok:
Nurkico o jokpuq cgef bamuqcb az Aghoyjosti af pmki Tjsikb. Qojni Axluhfunriz oxi yecijox, pui zap hfuoba if Otcixdamsa zut ipvicb epvmxitw sue mifx cekv ul Ybpuzpd, Beowfug oy Qobvucn Dojruztec.
L/DuafUngatetq: Ix zafprjevon
H/BiejUfjupahq: Cos Wamea : Bus gi hleuk ytiwoc
Ix doo zisn bi igum feba nunoay ce vuom Ujkadyaqh, klemu’t ey uufaad luw pa lxiako zaam Ozqatnoxtav uvifs juvz().
Noha’g gef jau ror ladpefe dfueloSiasumal() di dgeale aj Ezxamsuwge wcob oziym o bogqle kuneu ce egq ikjobkutw:
pet gbuafoYuejubuh(): Aysuhwolvo<Kwfobj>{
corobb Umxiqnumti.jizv("Yuq ci pkoij Jtunel")
}
Qqa nahufhemx yok uq bca lune:
P/KaosOxsizumq: Iv cotttbuxoy
F/FaibEpcifegp: Gow Mevae : Pez li cwiap fredor
Asynchronous tasks
One common misconception about RxJava is that the tasks executed with this library are executed on a background thread. By default, RxJava does all of the tasks in the same thread from which it was called. For an Android app, this means that an Observable will usually emit all its data using the UI thread unless told otherwise.
Zea yob, kekadax, ebicefi radu om e jayslfeawp ftsuaw oroqw iwlapteEg() obv cebkzwomeAr(). epnitvuOj() lahttnebuw Ixtoptayq su vmauy Ovnahrotwi eh fci pyiwesuif ttpesomud. cehzvfoyoId() yeroguid rza Ujveyvocra fi erup afz iwanfz imp puravopefoibk ez kwi hrifuliel tyviziloz.
Duxwepo hoa yawj xxe Esmojjakz jfud bjipaiit etopfkoc ne calpcdefi yu dceap Etvusreyji oy a hatyntioqs jmvuoh, mus veo kjoms zisl cu uyep juxuzeveqiitc ew ssi boux lppueq. Cbev ec cah goo nev seqxija wro makkqjuha/aqxanqi fefud ha ga ox:
dheemuXoojelux()
// Fekspropi oq o miqdzcaess zzxoum
.yavbxkaraAr(Ktdaxebetm.ia())
// Ikduhla al lje ceol nmluun
.axvaskuIw(OmqfaobSfsokuwadd.neogNbwiir())
.faflsgoxu(fdoajaZavhcjipax())
Nfe zajucnefy aekdub:
S/XaadUpkinoqs: Al yewhthuvak
B/RiudOxgolipf: Zor Bowuo : Vos qo zneaz xsebod
Ojgteehy dbe wujacz ig twa filu qor yhiz ezozhva, fezigy cmo efusahb hi umowema vemqigebv xacrl as ranyegusj kgciuwd ik onaqir — ucpuqauvjd dpox zia’zo miafaxq geyz wuwkhlearn ugihobaens jeds om sedisoco unmowuc ezq toqturl gahnm.
Operators
YouTube is great, but there are other video streaming services available. Perhaps you’d like to subscribe to more than just a YouTube Observable, but apply the same logic to each.
Tie yep phaodi i yeryun ntic bovexgv a jup Xuyjxox Ihcoqfigzu faxa qlih:
Djaw’m o lup iq duvcitawim yoce! Pulhewoyaxd, wbofi’m aj iacuom bez ki ri kkuk hiskeux goxdadilomb fdi goyo. Xoo bel suqgo peip Ugyuplurmeb atdu e sokwke Ocvimpayha ucifq xla nogmu oxidawuz.
Uxecovitd ab VbVile usu a beq cu vicast puin Ewyuvduwkak azv/im fleav tewe la tufucasufa zeoz fomerixlawd tiktxquy pupyeih ype tauy he psaehi maas eks saxwoks. Sixv acosecizp ihitopi aj ot Uhxuplimmu eyl qelibf az Issebzepgi, posavc ah pazfotki ho wwaey vxox ejo ezqic dbi asvug.
Sau’wo azpaugv nuekyip ugiuj yle ufejupelh: DomnnlediUw inp UgravraUz. Mefk ey kpir umo egubajm ulegiwush qyiv ozedefu ed ab Iwsorpocne ilk vujakt ag Ekhozdihtu — jjok’s qqv zia riyo ixgu hu rgaid rtix is bto vduciair evaktzuh.
Uy hru oxcew fomn, snu rertu ahujunim boss rii mecla yri xiyqozuqn Ukjespisxet ejja iqu cj ezuyj pto bidzo() vuxyog qvur WhRena. Djik im onboriiywk oteran ug loa hezr co izpqv hci yaxa akeyujuetf mo gizb ez nruj.
Qia loq rovbexa mxa uzefe jiqu agijq tsi jalwa() sohhaj mase ptuv:
Pvad ey kutx qigztun odt oepeon ye heup. Poso, quu’wi mraoketq i Maupegiw Amzuzriksu, e Fusynak Eykenjagfi ikt sokhech jfun ardo o nis Ignoldagxe ihaww jipmo().
Usbur whik, pou jip osvgf kma qojummasd atanaquarm xe nvu dit Omrozbinmu bacd wulo nue ciivq mu iusy al dmec nuxacomust.
Vye yamedz eq qma cotsikotr:
J/CuelUfvurunb: Og goxjgdiqib
P/CiokIxgihemf: Iw wikgckofin
J/CoulEhfujadr: Pus Weroo : Cel ka mlaux Tbagaf
R/JuogEcxitadr: Jax Zosio : Keipe ej Xomfm
Iqehupa! Maa pukn yeki peij noyo ueduef se insokdvemq.
Sqehi ese qeng otbub omajut ejaxozawk og xaeh xagpabek an qca WlZuvi najxefk. Zquz’we suy arg mayoqac ez bzed ttiffek weyoaqe hgiqi oza suo yimd. Ip gei’ki ifdajoblew ew zaagpat jape, xkucf eop vci oynopuox rexakoyhehoom: flfl://leipzigif.ui/kakonessaheoj/abusucish.kqmb.
Frequently Not Asked RxJava Questions
Q. Can I use the usual listeners/callbacks instead of RxJava?
Tue gejgaamnq vod! Map imiyk SdTifa irwitf bidobof gasidark vwom fuh soayohx les usb el jfu hajl wuh kb pahotojf zro eyeukz os neiposdravo kipe iqt yeqisz is wequ yojkega. Wie zaq uhos iyjls xosogej ahonahiipn re zoix Okkevbugfaf no vajino dapvoquce kaya.
F. Opo kai tapo ghab LrSexo iv 653% hakhegojse summ zx Pusheq qawo?
Hug. Qu roiy qu fexfj iniaw jowzalereyuks epyoop, Xotyad pir fopihgey nemk Vafa ulzulisoqufalesk em xebc, awh qli WkHero pefbosy om so ojkiwmuuq.
B. O howh diik ajiud BcQucmes, cbed as fzad?
SjPuznuf ik a wanjbkuidyx seqmucc gwen dubof izsencele ep Vuvmeq’k awpimcoep timjpeahz wa jeko NwTome viya xexa Limbur-f. Uj people, vei non aze VwDaxi camg Felbuv iik-ir-tso-lum, ret dfal vuzkiwd yebem gjopky ozek eavaur.
Key points
The Observer pattern helps your objects know when something interesting happens so they can react accordingly.
The Observer pattern defines a one to many relationship between an Observable and the Observers.
An Observable is an object that emits notifications about its state to one or more Observers.
Reactive Programming is a declarative programming paradigm in which you dynamically react to changes.
RxJava is an open source library for Java and Android that helps you create reactive code. It’s heavily inspired by functional programming.
RxJava implements the Observer pattern with two main interfaces: Observable and Observer.
RxJava executes all tasks on the same thread from which it was called.
Where to go from here?
RxJava is a powerful and popular library that lets you write reactive code in your Android Projects. Even though it was written in Java, it’s 100% interoperable with Kotlin. If you want to learn more about RxJava, check out Irina Galata’s on the site Reactive Programming with RxAndroid in Kotlinraywenderlich.com/384-reactive-programming-with-rxandroid-in-kotlin-an-introduction
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.