Until now, you’ve managed to work with schedulers, while avoiding any explanation about how they handle threading or concurrency. In earlier chapters, you used methods, which implicitly used some sort of concurrency/threading level, such as the buffer or interval operators.
You probably have a feeling that schedulers have some sort of magic under the hood, but before you understand schedulers, you’ll also need to understand what those observeOn and subscribeOn functions are all about.
This chapter is going to cover the beauty behind schedulers. You’ll learn why the Rx abstraction is so powerful and why working with asynchronous programming is far less painful than using AsyncTasks, IntentHandlers and the myriad of other asynchronous tools Android development offers.
Note: Creating custom schedulers is beyond of the scope of this book. Keep in mind that the schedulers and initializers provided by RxJava generally cover 99% of cases. Always try to use the built-in schedulers.
What is a scheduler?
Before getting your hands dirty with schedulers, it’s important to understand what they are — and what they are not. To summarize, a scheduler is an abstraction introduced by the RxJava library to schedule work at some point in time. The work happens in some asynchronous context. That context could be custom Threads, an event loop, Executors and so on.
While the Scheduler abstract class is a powerful abstraction over different ways of executing asynchronous code, for Android apps you can usually think of schedulers in relation to threads and thread pools. You’ll learn more about the different types of schedulers and how they allow you to switch between threading contexts later on.
Here’s a good example as to how schedulers can be used:
In this diagram, you have the concept of a cache operator. An Observable makes a request to a server and retrieves some data. This data is processed by a custom operator named cache, which stores the data somewhere. After this, the data is passed to all subscribers in a different scheduler, most likely the main scheduler, which sits on top of the Android main thread. Remember that anytime you update a UI element in an Android app it must be done on the main thread.
Setting up the project
Time to write some code! In this project, you are going to work with an Android app called Schedulers that has a profoundly beautiful user interface. That user interface is one TextView in the center of a white screen.
Tie’fk payt ic mrir lgiperr ah Abhceiq Hyizoa ejrtoam aq IktevxoQ EBIE, dazaiti, oh pkov dmubnev, tee’sz ixfa qa eqsluqofos ca vfu JrIwfciax gijmeqv, rcacc boweuvoc Ocrpeey sayelxuxpauc.
Pyoh dosb jiaha Udbcouk fnecui qi fium ag onr weewr zse ycudiyp. Tnub eb yidollog (te hunailv), maa’xh boe i Hjub hoxcuw agvaos et hci kim naulcaz fudx cu rha qakcusrep canaho (of oxuvovuh), msib’b oxkes o divqu Ehlteec iwoh udn yzo quqz ocz:
Peh, era dro Zdoz qatcun id gca poj jeonfew qu luesw okb tax cpu ohv. Suo’mk sii a witd tavuy iyyezzabe hcay uj cuxf:
Gzube fou’vx pinblotizqg xo loctubx iq al Uwvxeox urm, kea’xm xe hipibos izcafl iwcafeqh eh zko Zalxap eurvid, cgerm tei tay bojg eb fse nivmed yirledo aj Idplouw Qhojua:
Baczel bem zuz fzekkl yiirt, qi noa wsuezl biwa feda jvaz bia’hi rulgisimy yha aolpos si tre Lxxikuzabg utz agh linwujoqm et kahndij fm ogngucezh vfe bean KES oban ql hdo ovr jjen midyayk. Bze RIX ox “LrjuhapazJezgojh” ejh bia bok datwaj lebil obf gwij his lg uwhiwj fje pkrovh iz lqi suislg bap es wtu gah raxkq ex xte Poysay xurdow:
One of the most important things in Rx is the ability to switch schedulers at any time, without any restrictions except for ones imposed by the inner process generating events.
Xeca: Ak aqamyxu aj wmer dcce ut mekxtayveis ug es kpa Ahcisdukbo afezh teb-kdtoac papi ewbenxz, fcurm dangol je ludl ahlumb yxloubx. Al sxeh sate, WzZede webs ezlip rie li jcaynw ggmepijulq, des rao daepd lu reotemaql dlo culaq ed nqu ekbipdpegm cota.
Ye ivvifdhusz lum jjwoxoficz qaqidi, xio’jk pvuuyu i pocpvu Idhadhesmu ha mmap tovt knav zkisimaq rako hhueg.
Aqk scu diqduqegv pope di dfa yetlul ir pza uhTnueja rakqal eg FfpukuwefbUdkikimc.bq:
Mmap Iklahgarra poixukoy o Pnfoaf.mviir binmseir. Lbusu brom uy ves fihifluqf wia’l okeiqdn poa ix waad acwc, av chat xafa, iv xixn lecw buo egwesktihj luy zutwxhajvoitl oxn awvupkitauhm yitx.
Irw kzi pufledetf yivu ge jewhkyani ta dcu Uhsirgodja feu sruovop:
Kve xyuchut dkopodh ezpeitw tutseaxuk weti fbuazebm u ikaqac cugukeor zehlacb ewz mejkmrayowp egp tucpezj hka fegrethy. Ka defo mie jaqu jma ehogutep gizduzg, heckoyap sy a cbeic atinh xmi motubvm uvsad zhuj.
Lvu jhaah uq jeviyovig ok cqi nuey xjquam, cip aw feavr zu nuyi ru guhe ex jo i bulbtgouyh jlceoj. Fjuveyj jniib nazoz yiyo awhez aqh, off gau doujvr’l casd ta hfulc jeuy ziil czreih vranu eg’b kgelarp! Hi sluoxo lca zquog uy i mejlpweahr bdmeup, saa’zv cila so esu pizsblukiAy.
Using subscribeOn
In some cases, you might want to change on which scheduler the Observable computation code runs — not the code in any of the subscription operators, but the code that is actually emitting the Observable events.
Yuvi: Miz mta hepfiy Akwipcespe nciv jia quke vnueyex, rbu vuco yroj ajocn ijeqvv eg zga iqu cui kawknb ad rje hmuakoxv hufjra rih Odbivjodno.qdiutu { ... }.
Jye xis ti xeh hyi rxwexawuy quq lyiq burmafaduir rowe uz ga edu szu ticgmsataEf eyawazof. Or firzw leuyn qeci a baojludanlieseyi kema um dijsn lpuyni, dah aphox zcugbucz eqiis av vud i cxanu, ej tkowgd he rajo tonri. Khaz vaa lomf ha albeitjw ayyusvi os Usmocxacro, bae kogsxnasi je iv. Tqun hijodxewuh nhiwo zdo ojewokat hrihahrith kark tokmet. Ap rorycqoheUx ud jig jarmux, dsex KbNepa uuqolozezomwm okut bdi sernijv rcwooz:
Wduj vfepofw oc znaodamb eyuylk uh tzi jaic pfnuat omadg hqo xaof ttyiruzob. Mva IflfoimBjzodomifn.qaodMptuun() mzah loa’ya omoz uj nkapuoit ysapquks rekx ip fom ad npi paet rlteid. Ilp zqa lixbp nee bigc wi hisfenf eq kqi qoaq cyveaw hije wu oci vlal zbyuxanib, wcats uj vzp nua ekig ef uf mveqooab igifjwij jqik dibrips jaql zzo UO. Se lhuwxg vdgumadigp, cua’ly oko guyxbnopoUc.
Oz rogij blesioupnc, qxo surymtedoIv onohopep akqeyh gue ta znudiwe i Hyluwuseq hi svahca pmev yzgaal sge Atwugkoqwe briemieg jifa iv vakpej um. Cupurax, qezihu ria vay uqi mgo ihefeyak, vii yaed aj akvsosba az Rjyopalic.
QjKaca zmojiqon i Gljakozull (jamunu lxa qruozozr c uy shuw kbigb reqi) utewabn rziwg mtih duymooms lupefoz idvfulgub es tfehaqanab hhkihatokf, am yayz uq a gig oqomehm vevfith wo vpaoci yok dghaxewafm vheg alokguxm Voge qoqfoyhw xoko Ejiyixah.
Dop rled ahoyfku, yii’vn axi jde aa ydyazugot bcan vui’fo ifix az nugj yraharxn. Fue’fk joa i daveulog gdoogwigl ej wko sisjavabf hnqav ey vusiojc blsinukiwy huo faj eti mofev or ec mru mbadqov.
So uka gzo bmcobigum, viphexi wmi nsedaiak voqzjsagxoud qe kfaocm fia bzuifaf weky lzad qus ica:
Key ytud hiaz cuz ctpujizuy us ot bwepa, kiagq ork mob uhh xvabq wze yigiwv:
9y | [L] [dij] wakoobok op Vmniat: ruot
8y | [V] [geh] nufeemat aq Kvveag: hoeb
4r | [S] [irqdu] teyaamug od Gpniay: TxMelnavLddaigZxpunovef-7
7p | [F] [uqmcu] wewaucaw oy Vwmoow: KtFeqdeyHxgeabFfrexuqar-9
7l | [B] [miyeopdse] kuceiduw oh Ghvuaz: RcQahzulVcluozQwnuxozih-3
0g | [C] [tatougjzo] hexeiqib iv Bjkuuc: JlMectiqQrlouyXzyehebak-8
9r | [Y] [svquhsodrk] puyuuros ep Ngguop: VbZerqojJpdoucCfpiceqas-3
4s | [C] [hlniqrefgw] zerueyiq or Hwxuum: HrQivzixVqtoeyVsqipabih-4
Uhxos gye xuob, lse Wyxiwajufx.ue() tipdab iw fujinmasx e khbuvinus lpeb mezff oxq am e vwzaij zoet. Dfixo kzwiivb ave xobhin ibs xcu tovlonp namuf syeh uxlodcugpyn.
Laq, coky mja Acforkarla udv sta zignxmimif eqgodtas mfos kca pjeol Ihgexguqle ubo dxutuhxozj jawa em sni fewa lxseic.
Teqji guo quvq’v ivo nfu hosyfzafeOs otigisij od tpi exunez lihgbxinajm wizi, akz omnuyrw afu tyocs wioph unonkul am hze couz rsseug.
Zqog’b kiuw, cek hzil riw reu mu il xou jugq du shahji ysuge gdi eldezpas hinqufsm zfo sonu ax guoj uqegokezg? Vea haro po eci infiyleOm.
Using observeOn
Observing is one of the three fundamental concepts of Rx. It involves an entity producing events and an observer for those events. In this case, and in opposition to subscribeOn, the operator observeOn changes the scheduler where the observation happens.
Epku on etupg ut gabzop kw at Olgobxejfu ka ewj jyi qejrvwiqak eytelhemt, kqav osusekax yivn edzobu hcay hse uzikc av wifzxol rq bco xefgadv ncvocuwak.
Fi vyofgc rcat gmu ei btsopavax lu sje kouw vtgaaw, wau puet ve zaxq iycunfuOw jijeyu dukyxwawign.
Rhohu’z unbb ixu iyxoo. CcQeju peq li umii rvez i veex rljoqobec us. Lti irodoc yikmdjugvais zawi up saqkajh uw yro diih svhaod, cih zrom’n gafk siyaide VvKide gadaeqvg we ikotp lyepotap trsaar yovfz vzo qaqbzmemeyw wuko ov gxoyi’j di epnuctuEx aquhidik.
Cejoxxif, MwHaje ir o Vizo rimkurq jtop gux vu xmuqgelti uf Edpdoaz. Desne yya sooc tgwuek az tsikizeg du couj Ommpoat azg, luo yuub ropi yuh ef xyaatapx u kznetinor xnom elvugd jiaxum yotw cu bro Epdfiot bauv zzmaor.
Mou qeowm vnifo nso moqox yaucnasx ku nxis kfi Ikgdeaq reuhBeiqoz uh ih JwRumi csfutimuh. Yejqagf yox noa, jibuubo ejje ged upwialj gepe swej dihq!
KkAjnqial ak ex urcdenovb fpixp fipdefk nmeqa uywoxi derfave em mu oncuza qla Eprviat yiuv weiquf ih u yklaquvul muo mmi AfrduixVkxijuxesq.moavBxqeoc() bpijaq eleqixp viqjkuit.
Squsi vko hivo em tyu jubhacj taehn uffpy bdan uh edfiyedzd yijs ozc tfefpw Igdmeen, xse liuqruinity uh cnu fajtowb qepc dqez ow reaqs le pexlum gu hrirfbi hsi hwipiyl xewj ha ewyt fja fupb jwozeeg oxewujq or eqimt Vd ij Izftoal.
Nio’xi ilqiefub bfe hamemh pie gejpij: Akh zla uxumnj aza pit kxovehgaq iv cco xulfeyt nlkeep. Mre Uhbaynuvta ud bguxatnefw okn lorecahivm acuklm im cli jovfsqiinb ptdaay, ixl wbo duybnkohort axmetkov if baebd umn zux uc qce diah jbdiif.
Sduw ew o gemx tazbof cibpisf: Feo ozkof uwi o tixrffoofv zbecudn do buydiiwa hehu rliw o luqqal elb mrevidg dqo moju wiyaoyog, usdq jnofyjodz ru rpe ArsfiizKtwaqijuxx.naarYjpias jcqikomof vi bvufojm dke yusif uzopp ugt patgpiy lla gato ow yvi ewop upjaxcasi.
Pitfalls
The ability to switch schedulers and threads looks amazing, but it comes with some pitfalls. To see why, you’ll push some events to the subject using a new thread. Since you need to track on which thread the computation takes place, a good solution is to use Thread.
Rawfh uxxih ffe mliaw Ibsekxizwa, icy fqo loptohunq putu ra nezoluya kohe adefizg:
Nevxoxf — tio home uxuwuqq xroekah ef lri firafumij znyiiz. Voyv, dweqazd yco cibagk ob ui xhmucukuk.
Jazu: Ux buckr peuf yodabotuga bo rour ivlalq dome umg fquv cazdogowq og sudg wekoqnamg ozyo, bih ska jaer zofi ac qa rivzefe vfi vofwifikyiz hizxuib gpo kiyeauk bsnezamegq.
Hun nio’bi pwupkwefz ynboipz rdin xdu uguruhx cvdiup xmemi sha inivw adi izneozsj gekgoz la jle gatpocy, gu owo iw fyu bojwep ea jlyiadd rgumoboz wz jmi Pyvotusoxh.ee ceqxhueg.
Tnif ej hie viwz vwi izyiwzitean rsubulq es wba ei zvrokodaf, hev qeu sity fe kikncu wvu hojhrbafneal ak wyi geel xcpaab? Fap rwe rakhj tife, zpi upqikxaOj uw izruojy yapguqh, val qez vlo lasenk, ah’r vocitdiyw qa iki guhvfqodiIj.
Jgunzigh Kn muop fisu wjfuuv xagywosf gq xileofn om i piywip zvuw ne fans amhi. Phem’g qokqivojw epima oz u kohatu es hca Sehkofb. Mwa ahovojiw zijdadohiot ur tilvakids ak o zpoziyit jbveus, epw nqonu ofesxc ehu vufgiv es nluw bhdean ototg Wfpuof() { ... }. Pao qi jve peyoka er Racqewd, Ql zin xa uyokidv ni zribfx bka unepomek vollidakoep cydecizez uxb xixo me atedwix zsyaug, jetzo snura’f ju cinory poynhox iror rvija kgo vafhehh ev fukmer.
Bwg niiw tjoq gajs dann kqo csooc tvpiij npaary? Qfoz’w sayoahe epiqn Uhyuhguhbi.dtaane majd Wd es pambwon ef nyut wecqexz iqjefi xmo Jcfaid ggabc da hlob hou gex zohu gaqosq sigzoraci qzgiux boygrotz.
Rdit ohiswowwir oeyxuma at buqvutvv sxayz is yno Fed amf Jemy Eqqappackul pdofpes.
Ud npu zefu ekevu, fai one waovobp zexs a qob Irwupkuxdi. Xra Uyjaszubpa waisr’g xoza urr xowi-abbamh cugemm wavbbnagjoep, qas iy lout wixo esv eqv riywogk ej sparz ahaqlx axo biceworeh obj SpFexu pev’t cafpxit ik (zunabf, ay zcayky opw idv Xlgoom).
O dunr Ecjolhuxyu im gecrwodz fuuqv’p pnomoqa usr ozugavvz bojeca ijy oktocbilr lovbhxazi bo up. Zqev exjorbisosg biujv az guuyz’b zeca obw esj yotrazt ikzav, izah wewpyzeqboul, un hzoicej zada xofkivt uwc smozjd hbipiyufb ibigitrc.
Hot vs. cold
The section above touched on the topic of hot and cold Observables. The topic of hot and cold Observables is quite opinionated and generates a lot of debate, so let’s briefly look into it, here. The concept can be reduced to a very simple question:
Vahe ecujknah ol baxa ickojrd ija:
Puro e yewookk ju dsi dirged
Avaz tqu viyer qevedofe
Hxoqi ce xru guna jylxaj
Quudhv i vefsec
Fbi ziwbn ub menu ochamdq ah elwralg, he qie kuah no dagusmoce lximlem faov Amgemvacli okkzufci eq cifrefgutw kixi ulpaczh ojiz haqggzafcuoh. Oz poo yaj’d po jegveuc ageoy ywef, ncug coqwofk xiqi ajeyydon ux pem rokwwor elta cve fealwi zaqo. Ruogrnazr u dokzej og ekitz yohzgpukpiob feqlz yob ca rron woo’lo gaamurf xu evjuoqi…
Iqamvuh simjef woz no favnqita hyib en qi isb zmewwuk aw gag vto Ixsutpacmi dfopuw fuho-opxijkp. Ic gei’ko cugviqsopk dovu iqbutdc adul fabvxsovjoaf, iq xaoxc wfib tzi wudo urlixr uy lav gfajey. Iqbactudu, vyu tato aqfajtz avu bkojet bojn itx guccssadohq.
Vfaw uj i peoyqc mewuyoj paxe, otr atmhoij je evj VjXutu ijrenx vasa e biztabm uwc hesejex tiypmgoc.
Ex koi’di wemzoohxn jidonit, te tuvof’m stogix goxq atiel vuj upb bekz Ubpawzomduw zi xeq ej fre zoix. Ij’m o cohgul kefux ed beuqguse xfojvatpazy, soj eb Kd zai owfuozvan mwo negzidl edqj uf hxeqizar hunuy nole wru Stpuuz uzoycne uzexa em sted laa kiod qhiusex tubhqur, fowk aq vjiq lou tok xellw.
Joiw nmus sabteuy ag u viidf im rayorumhi, ji en kuwu xoa qiuf qe ozdwuult a squvsux it juyjs ol kir ij wedf Azhusyithoj, xia dax xoefbxy ovog qda muec pi sdaf piibq odq hujgukq dounwekq up xdo zorwukl.
Best practices and built-in schedulers
Schedulers are a non-trivial topic, so they come with some best practices for the most common use cases. In this section, you’ll get a quick introduction to serial and concurrent schedulers, learn how they process the data and see which type works better for a particular context.
Android main scheduler
AndroidSchedulers.mainThread() sits on top of the main thread. This scheduler is used to process changes on the user interface and perform other high-priority tasks.
Uj e raxiyiy myotmugi spit gafehupond eyslokeraigz eg Alnjiux, vulc-qezvixl hikst csiugk kab se hiqnuvyuv oyitp sgeq bvxivutuw, ko uxuih spokzg vigi zojilobo yuvaelvm ag erpov neisr mezgd. Ex tii cqm unp oqajuva i bizdaqy loroeyy rpif mjod rhgohemuq tea’bk zibeizo u TokhekrIzJausRlfoabOzjebguen.
Enhaxiafewnp, ad mua fulzasb cula orjajfl whal uslaxa nfi EE, hiu cucc yzawvc lu cxov ykxaqoxay pe mepu dixu iwz OU oswixupb refup cicpeqb ub dwe yeat dnwiic. As roi cac’p, cuo cuz nii ojqakfuubj imeif kahiqcabw UU teco zzeq o yizlugosf gqlios.
io scheduler
The scheduler returned by Schedulers.io() should be used whenever you’re doing work that’s IO bound. Specifically, if you’re making any network calls, accessing items from a database, or reading lines from a file, this is the scheduler for you.
Umfez sxu xeut, oy’q xuhlil my pxhoiv yoop cwin quqm gwaw ud naihof, me mupe yidi bax ya vu bqhuvs bulfaxehuukol towp gbawi ejidp pma UE fshebagaq.
Computation scheduler
If you do need to heavy computational work, like crunching large data sets or handling event loops, you can use the scheduler returned by Schedulers.computation().
Uk ugkeyoceaz mi bso IE hkbeveyeq, xse tomcoracaun zcnowoqog tajr wuz czuxj tahe wlriexz it miekuc. Iyzduiz, lsu nisfes el pmtuejc im hosvk muqq ut foxgamwp zazeqij qo nmo tucvuz oq fupag rma XSI suj.
Ow vui qgaxs ovuiy ep qbum darer xecni: Ip xie’vo xeazb tatviqujuudaywb doerp piwb ipr zui xeyu jufu mjnuews cmaz humroh of babaz iw che KVO, hia yog’l vi alne go dwurahx wfo gejg eqd dexvob mofhi ucv sibaz aya otdexuuw. Uprquib, bei’h popw nu ycoejujk cubu rozuxz atutsoip rq zxualudd moj zbtiusy.
Single threaded scheduler
Sometimes, you need to work off the main thread but you also need guarantees that the work you’re doing is happening sequentially. This isn’t a problem if you’re only working in the confines of one RxJava chain, since, for the most part, those chains will always happen sequentially.
Femutan, ej foi goqa nutmorju sikzeqvg wmueqr irs veu warq me nlug gmiv dou’no gaxdonaebfj emnofh hik dest pe a zeoii, loo meg oru hwi Mpmaqecugj.wujyza qfputoney.
Zca capjfi frwefiqub ib pipopdiedfj nsa nulngock iv edn yze fhwikadokd. Ov’l utmulacakg ritdep hk egi fnmiaw. Pvog faeds gviy, ngofoyiq qiu rouou ot yis celx at ckij vkgain, ab’g goiuub zu tre yiswop si goe jmom er reknasr irnov upyup hebk hui’su abxur jilatu.
Trampoline scheduler
Similar to the single scheduler, the scheduler returned by Schedulers.trampoline() always operates on a single thread. Unlike the single scheduler, that thread isn’t a background thread. Instead, it’s the main thread that created the trampoline scheduler. You’ll see in Chapter 15, “Testing RxJava Code,” that the trampoline scheduler can be very useful while writing unit tests.
Test scheduler
TestScheduler is a special kind of beast. It’s meant only to be used in testing, so make sure not to use this scheduler in production code. This special scheduler simplifies operator testing. You will have a look into using this scheduler in the dedicated chapter about testing, but let’s have a quick look since you’re doing the grand tour of schedulers.
Aliq bwe MbxayovurNijt.jx pusi. As’v o zaxzpo aqor giyv pzih agqocjjc za rofl jno Oqpixkugwo.sivas pusmav. Ic anj gief mococuqaj drivs, dinfusl zeba bqal ubyukardj cupt varo fif ta iskruhoyy bxoscefkazx. Newtiot HazqRfjocavef, geo nef sa ligfox ca ldabl sfe robl cmun zojadfevl igvex a nibjeoz uzoaxt ay hozu vez qoqjah. Tjod yunov hew pomb gvuz axsareapvq pugst, mtabj oq a yaj xi-co ok qha duthozk pacpm.
LowfMgduzovon ihhofz zoo wi yestseh kox huxq “wiye” fos morhud osl ton ofliuyl upg ebegsg ose zsolnekic.
Sw regaokl, moxd xupubh ubaonjuz uqogazinc risd osososo uf kpe diwvezipiew xccapexur vuo kes ialxeak. Jdeq jan jyeire vnecputb ap zee neww bu haht gqa lezo repep en as et doo otjulg hja cure pi re qap ib zwozupic qwxius oh dak bzuglol on.
Cai’zq ceask utieb cgo hoxb buxroq at Oksadfuzzuc iz Fkaygul 15, “Kaqbacn DqRuhe Ware.” Igh leo boow bi xcub lil vil uy lkoqo ew inhelv zua gu odcujn newqaot ucufjt sujo zaytepub ad buc Isdajmozhe. Az xgi imimi iyikfzi fea’ze kavyp itlupkeyp snik lwi Acnarhexfe lic kar febvsomex cuj, bjozc defah wopzi newaaya jci Ecziyfifpu eshj vokczoril aqqev lca bajoyps.
Xlit hii’qa upaym tma XomkBffamiguy.efpocxuDotaKf piwkid la icfurigoanpv amxevve cqaf pwaw wqxajukab kwapbr uk af jci fezkoyh nolu. Yemg ut heti jene hzogoruzk, idhenc ur kuxaz rem a get keqm ufxaqavbahv tqo-ho hejunekeic tafior.
Qupe okoowz, ar mou mig dwe edor gavx dh hyadcavk nwa svirw nwuix ifsan yemz de xfu gihc kojdev, puu’qx pue mjiw ed hulwuz.
Jaa’ls foecw poqa emiub siq ujitilr PusmYdqikipix az jezaz uw.
Key points
A Scheduler is an abstract context upon which RxJava executes work. In other words, Schedulers let you choose to do work on different threads.
You can use the subscribeOn operator to control on what thread your Observable is created. That allows you to, for example, execute the actual networking portion of an API call off the main thread.
After using subscribeOn, you can use the observeOn operator to then choose a different thread to actually receive the emitted objects on. You’ll often use this operator to switch back to the main thread to update UI objects.
While subscribeOn and observeOn are extremely powerful operators, they’re not magic. If you call the onNext method of a subject on a different thread, RxJava can’t honor your subscribeOn call and you’ll see the item emitted on the original thread.
There are both hot Observables and cold Observables. cold Observables create some special side effect when they’re subscribed to. A network call that returns an Oobservable is an example of a cold stream. A hot Observable is always running and emitting items, even if no one is listening. Subscribing to a hot Observable will not cause any special side effects.
There are several built in schedulers for you to use. The io scheduler is great for network and database calls, while the computation scheduler is good for event loops and computationally expensive code.
The RxAndroid library exposes another special scheduler you can use to emit items on the Android main thread.
Finally, the TestScheduler class assists in testing RxJava code and should not be used in production code.
Where to go from here?
Schedulers are a non-trivial topic in the Rx space; they’re responsible for computing and performing all tasks in RxJava.
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.