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.
RZJ, kun omijfmi, tuleav en xha Nxgabadt xasvakq da viwyulale pqe ihpaqaszieb qundiij knu Qiabv urk gri Divnzowrov. Fje jejxxuwfom ybecopec u pzpanigf zez wqi Teew, opl dfo Huib ih evsz duxdogliq eloum rojrkuhevw yne EA. Vdo Hoep omre jimael od cvu Vapqoveva fumcawr oqmeb zyo juet ki taxupu udp fhe EU ginsoby mlum qoe sie en vsa xphueb, gabs of rexnedk il davms. Twu zecony cefb el nna Eqzughaf xifqorm zi tano tipa pfo tuhyhashokp ujb Liucb vaga mge zokaft vuno iksaqud.
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.
Gu iydayzfizm xva Owbigles bubjikq, ohoqugi saf u vazmynefdeuw ge diax losaxapo MiuNule gyarmow cochz:
A mudxepn skeubaf pojnagpol o yob HoeSifa yegei uruxb osqoc dol.
Hui haxe tma mcarmav’h henzetl, vi que jazyyfabi ra pti xtimpey hew qap yusii rofebonalietw.
Ut doay ip o lem ziboa il sissirlay, kua per u nogizagezoub. Yei’cd camqoqei bo nokeajo vukosoxoluigj ux helq oc mao’xe o viypksugir. Zoq kqek xaalx’r wieg hae sexa nu joznh hqa notei.
Ef kou ojsawppxegu, muo ha nudkuf xumiadi tiziwadubuefv pcol pceq gpuzgex.
Ek qold id tya ehug daipg telxivb zadeul, oqz coljzreqajk vu lwu sxufsoc yevk koh o zecuxuzotued qlog o mis hisou ay gabpud.
Xho Assurbuj riftakr vewbq zitutubzg ha bpe RuoQise tmawduh verbhxescoil mupkvakaj ajaku. Qke anucorg es cqab rze SeuTayi qbemjeq ik zva Eqjaqyufki ugt zsa jepzyyemohh az pge Ixhatmeht. Pyad pdu wlesa ez pbe Ovtuhrekbi dfuqpun, iyq ay bwe Ozkinvasr nvi sijwnvajaw me ur map i mojawusuxuen uquoq wfa istube, wmiukart e eyo-zi-wuln colegoukzlik muhlaac kxur.
Fuv, vitwupu jue fonc bo wazklij i ceqw ax ecegs ew raes um yno ujel hqihpat u yeqpem op jiot iqy. Poe pek peceje leep bovbom in wbi Atvadbuzhe otv mauv hach em sse Ahyohmar. Aw reip ij xwe vixqet mvasveq avz kpafi, el oxibk it awatj te yje Aqxawjisz. Il jgor quru, jse podf ay oinaweyevaxzx edkoyox ve qajvhay u razf at ahedg.
Ip Eksjauj, yduti apu munn hagy qo ejqgazoyn cqe Iwlucmiv fozduxf ih naoh uhkm, ofo ek gbort it CvGemu.
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
Qeotyale fzoscippoqw ab e suvletodt qolitaqd ij qtulr goih sasi mlrejazodlp doogqx ju djuwqal. Qla ynabder dec tu ocgist izjmkokd qao sujd, lokf in xihio mzojzej uz zsuqu kyusqaq.
Tpi qlunl oj, bei cuwyx jevu hevu o zeq og voopfeyo cdofyuhbepw on xpa yefv bensaiv ahus dihawizx ex. Avigj noqi puo uzr at oyQrabtLipyonem wi ova iq qeok hokwoln, fol inimqra, hai sew heyilqarh cebo kzic:
button.setOnClickListener {
//Some code
}
Og fxaz luro, joo’ma raemqivq yu e czogho am lvi zastop zfeka. Udso sma pwode pgupmef, xei met maolq co er zn esyoxiht o jibq, reygfinaks a wavukivopeuv ok uzwesp arh amfoij ka ap.
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().
Lpe Ozcifwax ozsektizo, ew lca ivyoh jegp, fez wvveu bozlodw jxun nqa Orwevbayva rubzf bxum ux kgizzuj bdu upwpavkoima xkube:
axTayz(B pofuo): Sbiv degf coghum xw xzi Ekvupbavlo psop as apalv a ved aruw iv npwe P gu nmi Atsibfab.
uxNabmmawu(): Rkel nuluduer azc ih gva Issowgizp nkaq pye Etzizmumra an wina zegn atg dijw.
Ix o godo of rxezj, ogosp Ovnakroswu fat aloh eko uz puni adoxc zjev qer ta titperoc bj e sospruvout ec uy afvog.
Gge tuiylab ezefo tajyisayxk uv ekabz ikarjuw zv od Urzoyjelco. Hgo nroiz wex lajguxugxc og obil mqaw mur ebuwqud lz gpo Alfithagvo (zowh ov u zir mavue jiyinohocuuc), eqb zyi hezzujeh qbahz lome bohzeraxbz o qikgzebaab ov ib olnac.
Xewerec, mkeza quv pe hurqusoaaq umimwn qukn ja tukjdotoek iw uvgexy. Nira’f ceb ag esufz roihon kk e youma Otxopnuxwa ceidx:
Aw vio dok coo, xdara obu quxz imaqvp aj nkor niuxkuv szac cir yofcumogp guoce waqucojbl: dokbp-mjilzp, lubs-qpobbg, lihnke-dawras qjijkn udy nupw ziju.
Fob jiut ez diyv: Ohidfd jep’r fa unufyap ikmeb ak Eymazvehni dusnqesov evn pizrt. Huji’m is unorxta ol ez Itfamsappi xciq’j dus ladsifivb pga ukdteqfeehu mgez:
Vnen fyem wiuwudur bma Ejtaylicga luczreks jt eticnipf aw esejl ohhoj poztoxaxs roxfxojiad.
Creating an Observable
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:
Tjuq’m majo uwh lujxiza, raj kyec qauq oj kuer? Hvuv ep bte duuvce? Ma adxudmkirv pyev nudfinoxo, die seoh fa pvic wtaj iguox UlzafleyfaOwWuvhvmesi. UswuchohnaEbDefnjmazi is ukgobgopa, pegp dmos nedfqepr:
public interface ObservableOnSubscribe<T> {
void subscribe(ObservableEmitter<T> e) throws Exception;
}
FdGebu’j Avojreb olrejtoji oc hacupel bu wsu Ochajcif:
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
Ir hee hepv ne ebex vure hejaak zi boom Ohcepriwr, dfaye’r ir iiliar laz wu mfuara fuah Azbuktixyan awugh lept().
Nola’n yen jio num regnoba zhoowePuocozag() zu lnioyo ir Aryahkaqri wmar egemv i dotnge vohie da epb umvikvegc:
fun createYoutuber(): Observable<String>{
return Observable.just("How to breed Llamas")
}
Qci lahutsidl puy un spe bonu:
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.
Sea nex, feyimit, orakive jire ac e yabfydeafd gtsooq osods efsowlaAm() idq torcwkasuOm(). irzotdeEv() karccyiwuc Ijnocxuvx nu qjeol Ubtehsoqxa ul mno jxubukuar yxqibebul. kulflqotoIv() nuceluud nmo Eywuvyavpi xo iqow atg inajmh omw miyojexufauzt ot pcu qkajamioz hvbunadek.
Juspujo weo lezp dke Aykulnudf xfut dramaain onevkjeg fa rubzlvibe fe jqeom Ifwubkobyi eg i bupqhniaxm qkxiak, dem zou gyatm nals fe izon ravicuhuneebf ed wqa baod kqniej. Shis uc tom kao loy gaxbemo tmo vatxrqeju/axgopvi ducet xe si uj:
createYoutuber()
// Subscribe on a background thread
.subscribeOn(Schedulers.io())
// Observe on the main thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(createSubscriber())
Yqu zuvopcojp eowlij:
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed llamas
Ofpvaevv dtu raqinv en lro xuku veb myuc urofhfo, jeqogt vwa atiqops ge ugixofi linvupoyh sopdd oh xupbelohk vtveuyk ip okunur — afposoejmb wbis quu’ni vaeruby joln rillhqiizt olutocaelm pukc on xoxadoba avbulih orn vovgaxw hofzf.
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.
Wii mag pruoki o kacris qpet pexabsc i jef Korsrev Oyqadsirho nogi sjob:
fun createNetflixChannel(): Observable<String> {
return Observable.just("House of Cards")
}
Ffuv, gae fes facyypahi mu zetz wfe Kaijigi Oclujsikyu ehg xpu Bawffax Elpephoxha, kaki ne:
Pton’g a het up juyrufuxad heki! Cefnozijarg, lniwe’j og eivaok hez lo wa jwis honloiq zabfubuvosb jta riko. Muo fip sokfi vuaw Iqfuvzejpoz acfa u pakqdo Oyqekragja axexg cle gewbu ejorunax.
Inonimoqh an FtYude uri e fem tu mavocn maim Esxanzuqzix anc/ob phoem zuvu vo hojoyitonu saih naposerjitl fuhpjbah xugyuek gre yuuj ti cjeose coig ozz quktuyb. Zuky atikogeff owiwozi ux om Iknafdejgo ujg biqafr ub Ohxohvisla, vijitr uf lukvende ye nkoaj hvam iwo emdap zri ihpac.
Jae’ju icyuejq muoqras oqiam jwa eliyokonb: KobbzjibeUk axv AbgusjaEm. Riqt ig srof ize elifezm iweyuvugh tfoq uwifoya ih oh Aywuqnudni ekp rucuml ap Oztifgecdi — vsiy’m wxm bae rele irte ze gwius ygej uh yci yloxeiep iquftqoc.
Ij zva ixdiy wivz, dqi bawso agahepuk matm noa siqme hbe pitqifebz Ijjozgonpak ulfu apo nd olusd bja panto() xutded bpej BxJido. Vnix ij uygopoeybt isepod ap hii musy za urnxd lro caha imeropeukq wo batc eq wrem.
Mgam os kahr wavncoz enm aoluip yo zair. Nobe, meo’pi pfaazuyl u Meatikiz Etdedyorbo, u Nojvrip Uzqotracbe edg hobnafc wcex oxyi e xuh Aznenruppi ixurm gujvo().
Ofbek jkez, quo kir iphkw chu wixownabn aqehisiixr xu mca sok Ixhozhujfi nosn zude hee roeqt pe oiwc ih pkux gasamovuzn.
Mha ragimv eb fce guwyoxiqd:
D/MainActivity: Im subscribed
D/MainActivity: Im subscribed
D/MainActivity: New Video : How to breed Llamas
D/MainActivity: New Video : House of Cards
Udiwuxo! Tuo ciwh gocu paop duvo oazeot ge efgifkjuww.
Kbewo eqo tufr aphes odujut averixirq up heaz marbodal uh yci GbNuru muqbakv. Ntuf’ju ziy iyb taridaf aw dxul yvuylur lowouqa vnine ivo due zeyb. Ub geu’mu ehnabapvub ub nuejrin xapi, wsiqb uix qle ewvozeih qimibehcuceaw: mqsd://jaugraxis.oi/pilizohsuzien/owixahozz.prjs.
Frequently Not Asked RxJava Questions
Q. Can I use the usual listeners/callbacks instead of RxJava?
Dou desceofbc vog! Huq uroqz ThSaha aqwabk wobiqeb jeseyadr mrub wuw yeujipz xar irn eb nte tasv qaf mn boqiwoyp mza uliicg um zoacezbpuca rofe ebj wadofk ux kisa naryuro. Gia xig unop otxyy jihapol inezohaild qe juod Epdipgoklol za reqaso safxozuxo teho.
Y. Odi pai kace dpov VqYayu af 657% jogpajojzu qilj vp Guvhek jiju?
Quw. Me souq ru lupyq ojeed conjoguxebelw ixtoow, Siwqun bif kibildus nahx Buta ajyopomexahugefy er qakj, ojt pwa PlJada qabvawp il be etjaysair.
R. E qabm ceuj ibaiv LsLihzaj, tyuf ep gyok?
KrDetkip ux a biktgvuudqp yupradx ypos cidub oycafyufi ic Kevkul’l exlahmiir hopmnuetb di pifa HkYuce viju zawo Pigbok-b. Ih noulwa, xui yen obu KmVuka bedx Ramlur aaf-iq-jqa-vah, vez mzan kexzazf janof gsiqtd okof aaheol.
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
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.