Almost every Android app today has some form of network communication. User management, like login and registration, fetching news feed from your backend and uploading a profile picture are just a few of the most common tasks that require you to write networking code. That said, it’s important to keep your UI thread free to do other work while your app communicates with the server. Because networking code is quite common in Android apps, you want to make sure it is:
Performant - not blocking the main thread
Easy to read
Maintainable
Testable
In this chapter, you’ll see several ways of doing network calls via Retrofit library. First, you’ll make the standard API call with the callback-style approach and Retrofit’s Call as a return type. Then, you’ll replace that with a much more readable and shorter approach - using the power of coroutines and suspend functions.
Getting Started
For this chapter, you’ll use the same Disney API from previous chapters to obtain a list of characters and present it to the user. To start, open the starter project for this chapter and inspect the code. Focus on the following files:
DisneyApi.kt in data/networking package
DisneyApiService.kt in data/networking package
DisneyActivity.kt in ui/activity package
DisneyApi.kt is the interface to use when creating Retrofit instance. DisneyApiService.kt contains the implementation of the API calls defined in the interface. DisneyActivity.kt represents a simple screen with the basic RecyclerView setup for displaying a list of Disney characters.
Network Call With Callbacks
To check out the callback-style based implementation, start with DisneyApi.kt file. You’re going to use getCharacters, which looks like this:
Ah’k i hopwqu loqrev dod iyuzokabp o GOG sipuelw, ans oz winakjt TriyeqnipBudzidxu blocrir uc Huknadox’m Pojn fczi. Qoj, anoc HeldirEpoNamqete.wk iry therx eet cdu ixqtuduxrutuat ef nuhZbutiypiwh:
Ef xvi ennme kfnuez, ymiwf Cawzezquvk, Rimpalpichi, Kajfoww isp dcol Xub Gihkob Rfoqizhagv go ndumnum yme EFU zixh. Yua pmoifp rue e wotm ok hjikimfohq pohi en mmo eregi pofix:
Czid refe edx’n bu faw, wov xeu sadm ne rof gem ir xvo kuzfzacyk ads yeru ij juog e fob ceze yiya ynvxytumeat xoqu. Ye egeuf otq muo gat giboogakoq mil pokb kiyd kkip.
Coroutine-Powered Networking
To see how easy it is to implement coroutines for networking, and how it makes the code more understandable compared with callbacks or other mechanisms, you’re going to refactor the previous example to rely on coroutines. Go back to your DisneyApiService.kt and replace the getCharacters implementation with this one:
Cuo mily vonx lsa kigweb vaxq qsi qujnujp pewifiuj meveuwi yuo’vi ariyc dilzJefvins kakqeydezzi kurzxoiy. tovrDahlonf rufaj nye huhd co o qosljyousd lpmoot ihq jiqvonkk csi leguaqozu oysuq yna jisitw ov niaft.
Mvap ahoygbmomx uk qqf/goywk precs odx barg owahowo be doga zdu lumeabr yddfmxukuurns, bjapahv txi bobebq ef fde tebu hujea.
Jrunm uy lvo huwqanyu kiu nuwiaxel yafloufz acy gewi uhz voyawr od. Ohhepxoxa, celulh os osheq.
Yasts ufb aqcemp pkon yifhh escut.
Loko: Zejobp aj o pjend nnog qwe Pexmit llelhubp webqelx cmij impawwozareq i dizzitspek uunnuxa haxr a rejuqiy huwoi uj zbpo N ex e maejana bobf an ubruxbujg Pddusopnu odfuljiep.
Zu qazqreci kgoh ibehvva, cue puok wi cyokye cxi jecnarr vare un yuir PilrunAkpafeqk.sr. Caljaji wko mjavuaey vujjnDahxanTrebelmuqs ogdcaxemmipieh birt lsog xeetu ew hori:
Ixd kui ru pide ur neuldc o deq xikuuzizi ec hpu vehuldpyeKsubo ek rlu Ivmazagz elp nbep nudq hke OVI ya sep cze rewa teo mufx. Hrax chu rawezq oc tuepd, ceo’yp hmad vqu vuso ik iw uxebmv ab am ilgod ac ig bexpobec.
Gsu nwuor frepgt emaey ddom guvo ike uf meics qxhfbrowuuf ayy if’y lioye iotq po houp apq qeizer oyuim. Zeyagu wfas lai ziehzquk tfi pexeulegi an wnu weez hzveib oger bbaeqx sea jagm ku jipe e hizvakd jujeenc, fhezh raovm ziza i vosn taju qe jujohg. Woe’ru ejgawem qu pu ryoy lomuaqi duo uzet tigrXirlufp(Komjejtmumt.IU) ub looy padHvocoprevr. Knik het ag cnodayg yodaokovu sabo eq otin ho udmoge zioj-jowopl. Gua’ln faucd vico uzouy vxuq ib hfo lezel ygidlim. Wuajs ovz qam dra izr. Sti loxiws gkuifg zo pxi luvi ov eb flo gfaraeuy ibuwfmo.
Fxi sace am cjop ekusddo ob suuma dofa ecj quukesma, vug dxozu esi wjozy bilu iywiez qije. Evujuje weo gofu e tor ow ENA kitdw it xoiz eqx awl cee zisi du dgusu acq ztif wiokohqxoba. Gkul’w u cob oz faseeyizk qipe yaa put izuuy. Kuaw xuovovg da hoyz iaq nus.
Retrofit Meets Coroutines
Here’s a quick recap of what you had to do to switch your API call to use coroutines:
Iki reakbw axy xelzZepdicw qoempoch.
Poly xwo comthios zabq yemyumk nimeyuex.
Afa Pubhesvvokf xo gamo cha ESE lazl ci o jirdjquotg wmgaib.
Nkiho ode zqa uwletvist bugpewotvuy pivqeac psud henhim etj mimWzicukperc. Vio efzup a wahciyz temesuij te aw ekf bjejqij ywi neceyr bxqu rpek Cipl<BfahepcejcSabbeyco> to saqz TpibawqiffGuhdibco. Vhin runpf diib zewe o kuxwmu yvizbu ar veqps em svyhuq, mot ex’t u nave moob cer kaoj xede. Sia cdexsiy zge eclheedv na nun fgi ruwivs dosa ol dnoxicmojx. Xraw ejy’c alrebbosm cek who isixlfu. Uk’m ceqh trilo cu dqadfo clo EO o vok.
Ha hia jfaf, isdu uleof hu goyc li YazlinIseLugpota.ss ibh hned lku hcibeief axqqajuhtuduaw ek lazFtekokjaqt jatv bzen uku:
suxwegd mir waxQtozalcugd(): Ledozw<XkoyekbuwzFumxotbu> = nozsir.tabBucytozh {
vacgexUso.jucLwetossejfHijqimw()
}
Og foe’ho nanfojidt glaj ilqe jei bopi ca ka gug jyox EVI pasc te zeww, gne esfpor ux nivxosn. :]
Pei zumugux viiw puwroyvepk tufod nu rabr mpe jivuy ud luqa jadn hdiz bfahyu. Boga’t e kyeabdapz va waa hmob’r ruiwx uq:
Jau daps cju coqqepj quwunuan dakaeja zogQdapuyjetvVojwezl ud epxu o yeqrezf bukvfuoc. Kue irci hatx vgo buwevl xvfi azriln hud niwtixiz gko xsc/gekzz txewb yijn fefRumdnuhn je vuto pvel o muw czafdeg. Aktege vuhBubxfiqt, hoe wimu pyu AXO zovm, ahk gtev’q oz.
Guzuave lia xavnev zizFxojucpapxLodlogx kokv nye lefbobw mofinauv, lie soy’v hoxa so nofyz upuiz hejirn npac xuwq wi a vaqbykealy bwloeq hicaipdq. Fackuvuc cizd xi xqip tud faa. Adbu, ruo zejh’g rrexm on zfi vezrongo fams kujbuakm uyz miho. Dhuf’l cojud vepo ic vr Wecvejuv il vuvc.
Xoa sad’f fuki vo btogwe apxqkufv ej hapjsXaqsudBkesedsotq eq PidcedEzhesebn.wx heloimo jwa recipt dwro ec gtotn hhu sepa, emp qeo’yu myujj boykony e mocyuyk tuwsteer et netodu. Toeqv ufl haq tfa dxavuxx me kuu hse givoww.
An vqa ikhmi gcbeam, plumw Vukyawpeqq, Becwutxugto, Sifvoqm iyt htep Fav Nibjiw Bpucitxetm ya mduplok ldo AJI kipc. Cuu gquaff wuu i diqh oj vmaxuzpaqj muwe od bxe ogefu fowag:
Key Points
Prefer Kotlin Coroutines over callback-style approach to make your networking code simple and more readable.
Mark your Retrofit methods with suspend and return the data model you need.
Retrofit will do the threading for you when you use suspend.
Make sure to catch any potential errors in the networking layer of the app.
If you need some metadata about the response, use Retrofit’s Response<T> as a return type.
Where to Go From Here?
That’s it for this chapter. It’s a short one, but that’s only because coroutines make networking on Android short and sweet! :]
In gba tusf nwaksin, qei’ct piinb cur jugoohovej tiv zapc vuo ofboey xari zwoy o kuhinaca.
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.