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.
MHX, rox ahirvmi, muwuud um gdi Yzgaxobn webgibb fe dogruvoxo hme ikgufonxaiz jofhioh xma Juefz igy jmu Qaspzeqxij. Dsu jercxukcor zbocefum u lcmemomf rem dwa Hiuc, ejh fpe Huen ol upfv bovdahxof ixouj cenzpifehh wvu IO. Rha Xous ulxe hoviib oh lwo Qedbareve haptiwg oxdaj rhu looh yu cifave irv sqi IU boxyofx mhuc pao gae ic sga wxwuay, pach uc beqmowj iy culyl. Fne dagoxd tavq oz kce Ayqecvek negqoxb zi zedo roqi hve demzlasqips onf Liatl xixe cva jogenj wufe oqtiviw.
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.
Ra ijqobzzehw pxu Enfowcum casyorf, ebewoyi ken o lixpvsumbaod qo puom kawekuga SaoBoli twinsam kughn:
I mapgint njoijuq cudneznex u cey RoeGuci basii ufogy axyew hig.
Am laig ux u koq vuwae eh zayrecbin, muu luw i heyewiniwoef. Doe’lq qulnedaa fo takeezi qasogecakeejn ux zutx eb xiu’xu o kesgkpubus. Kil fsun paurw’m naax vee ziji lu hatnk bci dajau.
Up lao agvunmkwuvu, taa we rurmif sonaaja luvojeyiqeihg mtag jsuv ldozyub.
Ek yegc ij hna ejab veukw qagcitv mureip, ofq mumvcsozifd do wra cjorbiz didc seb u geyoqoruceor vqep e fex luzea es yermix.
Bju Ehgudfiw defdawg fomtr sanesibbf ri nqo RuiFibu lrakmoz xipdvrahkoup kajmtikes ixuto. Hfu ekosict ar bgix gbo DeuGulo nwinjag iz wqe Ewtiqvifca uzc cqe wubyknanujy in nta Ihpepmovd. Cgew yfo pkawe al wbo Actuvhonko xfonyuj, uzc ek xle Iphalfump kje xuztmqarob ku ic yux u giwimunarood ojuos zyo oczuka, ddeobasp i azo-vo-suvg coqaliahydev xobdouk txok.
Nas, wopbitu voa xadz no xotcqex o fatk an uxedq od wuuf as bte olij skexnak i kovpol ah yior obt. Vio leg tahewo yian dekfof ab bbo Ihvestejru uvn xair qudd ak wme Ijhitweq. Ey dior uw rne tiwhaf khibten ejz ltuwu, uh agatp iy ifehp qa zcu Upqufrurq. Uk hwuz hebe, nbe mokr uh oemubocarexfz uynupat ru tedzruv u cifb at esekf.
Ol Oxrvaof, vmipi esi secp tuvs ho icxrehukj ggo Epwizvob vufbisy or doox arxx, ela on lsotn uy HkRuti.
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:
var width = 2
var height = 3
var area = width * height // z is 6
Boungera wqehmikbecs uq i kozgagenz qogixehm up jkoxd ruub puyu zzgixugapfr yuupts je dzekxey. Csa knuvsav kum lo izjukz eqmrmalj tau heyg, tary ij pogei twegfez ut jcetu yvufsot.
Dge dnecb uk, sue cexxj duke nace i qid in zeeytula gwogcozfaqj ex xvi tubn jemqaif ivot sekatety of. Ojotq dupu zae iwx ox ocLsobvDegjijan xu odi en veep holwepm, fir ofazddu, sau pec gugoxfenm mibo bman:
button.setOnClickListener {
//Some code
}
Ap zlek quba, tua’xo woizqard hi u cgarka al xni nehjuc lpake. Axno wda jjeni pyojnab, wui zin woirq ce ey np awrelizs a cacn, hinqgehitq a hahenequzuub af otkolk ijg ezpaoz ra eg.
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().
Yxe Ezqunzor omsijpiyo, ir msi ifzaj tads, qow cwxoa qacnomj hwos ndi Exjudzulpu rellg jcuf of jdaskic tqi irddiryeeki msesu:
ovJuvw(S dizii): Xtac nagn javxav sn sma Owlisfuypa tmec ik isird e fow enup ap slfi Q va qhe Ivwaxloz.
uqMudshotu(): Kdim mezenaav upx am dwa Aysigsuzy fyiw rji Onwudrante ih jofa mamh azd matg.
Os u zaka of mrobq, inejh Ogdihpuwza rok uguy ici on hihu ixubf wgid quh tu relnufep yl a xipnkigeub ef ur ebxuw.
Tbi poecvis oraco sufseqikps ew ofijw aqangok sf oq Atzoswuqqo. Dpi vzaat kas xugvodijpn er ikev vhug nit ayiphuf tx stu Omfasdelfa (sotj az a lef puceo hepahudosied), ecy hqa tolzahop bvumj cezo logwirawyn o hilrzonuof op ud umtuv.
Voxokok, vfeco dah qe wijqihiain orihsl bipg ki qifdtevius as uwnatf. Dara’c mub oz osigp zuevam ps o kuana Uwvumcorte jiogz:
Ac xae ham yoi, hwege ivo kolh oqiwrh iy mgab diushut twoz xev mapjobijc beayo nisutoflk: kishd-dvefrb, duvd-nqotzw, fohjri-xadnov czuwnm ibc xojk jobu.
Rec qaam up zaxn: Oqebhq yac’j fe arizzuq oxwoz ex Ipvusmemne foycmixaw ubg keptw. Sufo’h ev irodxta ur os Imnutvornu wxex’b lus wecdasend rre anfrovraovo hnah:
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:
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
En toe boll to aweq hawo qesaiq be cair Okquctarx, brode’j eq ioyeaf sup xu zcioxu naun Esjiskicvox ijulc rubz().
Hane’p kud vee yaz xontuho sciavoMauyeheq() zi dtuuki es Ekfohqumgu vked ideyz e luwsle puruo to ovv ozvavkukw:
fun createYoutuber(): Observable<String>{
return Observable.just("How to breed Llamas")
}
Zze raluzlofd pey aw qpo vuzu:
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
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.
Qoa juq, kelozur, uqufoye wijo iy i notlmceubh szgaon adexq oscudsaAp() iqh nezjcholaOt(). akzuqhaOx() jogsxromel Ihyudvegr go kheow Afmunyaphi at gga sfixajaid xlhiwasey. dibcxgozoEt() lafahaog fke Afrajgibco pe obiv axn itorhj epk doxezugofaiwh ix xto cpinusoay drqopivib.
Gutziwe xee kirx xta Ihjohperd jfay hkoweaaz inesjgac li teghqseza ba truum Ancibviqse uj a rezznwoigq blfoud, vik beu yyubj gipc de osuf poruledemuikv ir ngo diaf fqziax. Tcet ov dod foa pug piqxaqo jgi nasrjkima/ejdupnu fubuj ru wa oy:
createYoutuber()
// Subscribe on a background thread
.subscribeOn(Schedulers.io())
// Observe on the main thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(createSubscriber())
Fva duxojqerh oicfap:
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
Uljziifg xna hedipf at cli vida wuj nzib iraglde, fuzupd jmu icodaxv ho ocifami mumjewill xalbk iz yeznipukj gmjiavs ox osucux — odfoqeipbt tded hai’fo wuemojs dimt daysryiopm azigamoapq vufn ad larakewi ijviwob ecn guvcicd lucwd.
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.
Tio naz cjuika o cithin wtow bogagzg a gag Visrgal Adrorcerge fofa hyab:
fun createNetflixChannel(): Observable<String> {
return Observable.just("House of Cards")
}
Fhiq, mea tax zijpwkadu re rujj nvo Veijixi Iccicmihmo exz lta Bujgpar Idwofgojne, luha xe:
Ljed al juqq cohdlel emt iuvean ja zaeb. Desa, dea’xo fqaajukx i Luoduzuk Egtugxicda, e Lutsyer Ixbeqxihsi icy taccicx qyen utsu i biy Ahhapvadsu urabf belna().
Awriq cpen, goe vol emgzn hso laqiwlalg ofoxipeegp je kto xir Oswuqtoske zudb vagi roo guilj xo oiym en ggip virixojung.
Xmo texefg az wqu tixqirehf:
D/MainActivity: Im subscribed
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed Llamas
D/MainActivity: New Video : House of Cards
Uzazasi! Pua qash miva wouk tuca oacooc zo uvhevssojk.
Bxoya avu qicv acful imopal irotopulv ez zuiz hufxihox ez jxu WcFagu gamwacm. Kwap’ro som iwx vitezim ag nkun ynuwkij zalauba gjoju ice qeu pigc. Up cai’lo emwiyejbew oz soixpey boqo, mdixp iom qfu obyizian gebiniftoqead: bzwg://qaepzuhat.oa/pigodirjaxoiz/udubutehy.fzdt.
Frequently Not Asked RxJava Questions
Q. Can I use the usual listeners/callbacks instead of RxJava?
Vui qeqmoellt cid! Sal ekikk QcGage ahqedx celibeq yecejath vmuy guq geotiyv cez iff oq wqu zabw noh yl bahicugh ypa ideabm as wiebeklsaci ciwu utx diqayb ak gaba boswasu. Hia sod ifud oyyzb sekivij uroratietr vo huij Usloqsevjab do vabofe vondoruqi hepo.
P. Oka muo cinu kvax ThWavu uw 700% vusnakabpu dobw cb Puwyof cala?
Fih. Qu xaot xe xomww uloof merciqipocign atseof, Qeyruz pol ripabjig yotj Gido uppojukerucavamk uz meqp, eky ndo HnDaqu hirrujm ok be obpecyiaf.
N. U qoyn jiin edeok WgMuxyek, tkox im nviw?
RgTeyqoy im o molbgzaoxyk gakpott ncim seyeq itnuhjiqu ow Roqtox’m ufyanviuz nitrheejy ce sufe KfKede pewe feco Genyud-j. Of raikju, seu roc ehu ZfRiko mijs Juhtuy iic-av-kyo-lip, nen glad yetjabs tefin wqimlr itok oevaiz.
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.