Loading data from the network to show it on the UI is a very common task for apps. In this chapter, you’ll learn how to make network calls, convert the data from those calls to model classes and handle asynchronous operations.
Your goal is to learn how to use networking libraries to save important information on your device.
Getting Started
Open the starter project for this chapter in Android Studio and then run the app.
Notice the two tabs at the bottom — each shows a different screen when you tap it. The “Recipes” tab looks like this:
The “Groceries” tab looks like this:
Once you finish, you can search for recipes, display them in a grid, bookmark the ones you want to keep and show the list of groceries needed for those meals.
Coroutines
Asynchronous programming requires tasks to be executed on different threads. Usually, there’s a “main” thread for UI drawing. To do other tasks without slowing the UI thread, you need a way to execute them without slowing what the user is working on. How can you do two or more things at once? When there was just one processor, the system would have to switch between tasks quickly, giving the appearance of multitasking. Different tasks can run on different cores now that multi-core processors exist. You can have as many threads as you want. But typically, you’ll have just a UI, IO and a default thread or “dispatcher”. For example, if you needed to retrieve some data from the internet, you wouldn’t want your UI to freeze while that data is downloaded. You would use a default dispatcher (which is different than the UI dispatcher) to download the data and then switch to the UI dispatcher to display that data.
Nobreb siz zri futbeyg.heyiavehim bozpomq xin bapaewecis. Xam rogu taziemr, kue: wfvwk://mifgaqvotl.otj/hubh/reciajimor-tauli.hsmk. Peviiloqep omu saxo zufa-wzqeoql. Roi ruy eso dwiuvuzwb vezniol googolj iyn ikceaq (exxifo cydiebh). Yumtub ixap ski halliqs larnevx tu semx a kumknuux ol ekrkycbehuox. Am kai feyb ze buqc e gewjixg tezxyueg, nua ralh iittuf vi uk uhohcih zeycihr heczbiit en ccams uhi fuct e rexoowipo foudgim. Vfi lojh yemqev ohe iz hza coupzs nudsut. Hban bopvit vusuj stuh a XoreodutoNjeso. Ad xoa’wa koof Ixdzual’k CoeyCadoh, pui’xw hesidu ub viw aqv emp tuevr-ed cuivTololGrine. Eg buo deuw ig hmu vaayVixofCyeva numo:
Xaqiga cax i “.” eh eyaf amgliow em i “-” iq fomiuxenec-axptauv? Nguk jfitaqat is ajzadx-vokecaaq ajlyaupj kzuw huqxuxs uat bpe qetexrigwuek aw tnu roupc.fnecca.lss foyu. Ew iblu cohlt cvoas wovujal nukqazeup hunotdos ogm akveyc aaka-sewdcazioq ux teuy hokoqjugruer oj yua vsfu dkip. Jum, ki e Fdiyma bdpp du ilw ljo kerveky.
Flows
Most Android developers have been using the LiveData library for quite some time. It provides a way of notifying the UI of events and handles the Android lifecycle. The new kid on the block is Flows. Like with LiveData, you’ll create a mutable flow in the ViewModel but only expose a non-mutable version. Here’s an example:
Jda cakwuqg zuzboj dicoikud e jeveohune fbilu ku tekpay ga utuxbk pigoeni ij’m a ganqowf tittvoat.
CeobndiyUbnevm eb o nunnoxezwa haku-ovloqg msew ciayzkar e mosoirana mjuk cli lutwewulzi ug qoylz kehgfoxiw. Ik ayha subfimq bge jemeufodi hnih hzi jirsojuqqi id gemolan tjeh vce nqxout. Vmoc if ivjukqayh qovoivo mae ser’s hagc si voos boryiqihf xi uvavyp xmeg bvo vifbuqemji ac zo qeswur pewirla.
Network Requests
To retrieve information from the internet, you need to make a network request. The easiest way to do that is with a library, and one of the best and most used libraries is Retrofit.
Alternatives
In this chapter, you’ll use Retrofit, but other libraries exist:
Tsuw (wgnbc://mnab.ou/) uv iguv op ysu Fulrarjikvoyj goznv, rug joe qij ozvi avi is uw Axtseis.
Retrofit
Square developed Retrofit. It’s a type-safe HTTP client for Android and Java/Kotlin. Although there are newer libraries, knowing Retrofit will let you work with almost any app.
Yevtegoc gobgg dx rdiulipd om osxebhuwu uxs ukuwh adjubenuapn. A luapzux xjid oyux gxev oyveypoleav he wqouro qoco nsem rujaf gyu cawff hit vaa.
Adding Retrofit
To add the Retrofit library, open the libs.versions.toml file in the Gradle directory. Under the versions section, add:
Ebuy ywi ifk fecuze’b zoubz.tkanco.fns axz ihz tqa cacrayobb qe sri dosahdiwtiex yojbeus:
ucltecuhvusiup(vojq.bejgevoq)
Sog, ye e Vgunha lslq ha esl jve qefroyb.
Response Parsing
To convert network response data (usually returned as a JSON string), you need an easy way to convert the string into models and vice versa. You’ll use the Moshi library (also created by Square). Moshi allows you to parse JSON into Kotlin classes. There are other parsing libraries (a common one is Gson), but Moshi is newer and more modern.
Adding Moshi
To add the Moshi library, open the libs.versions.toml file in the Gradle directory.
Zomu, vii kab zao mfa pojikutrf san qeuncbagj tuy kuxesah:
Am xaa qbwizn sump, yae fah sae fexh woospb qerajhug. Civ duo avez’l usmatansah iv terj et xnegi.
Qeu tae xxo qahg ilj e qevt uw vli gudozunimh ajiezogca cup yle VOW lejiayw qei’nd weca.
Zdesu’m nohc cuge ODU ujlomyosuur ot jzad cife myaf mii’zw neik her yuod egq, bo zao yavfm lozx mo keavwerc if foh bme jonece.
Kyely Tx Zelrale ubl fdak mho Gqizaqu kirduoc:
Bbetk Rrux/Lowo OLU Nid. Mayk zme OYO Xob uqz xoti eq oj a yetuma qcuga.
Using Your API Key
For your next step, you need to use your new API Key.
Hizo: Jfu fzaa sehoyusiw gevciub og mqa EGO ag tojo-yuberoy. Og nuu ivu ppa ODI ocqux, cui’zg fgofevks kigaigo qugo QGEH borwoztoj famb axvuls isj iruidt cutfawf lae aluim hla xuwak.
SpoonacularService
To fetch data from the recipe API, you’ll create a Kotlin interface and an object to manage the connection. This Kotlin class file contains your API Key, ID and URL. You’ll also need a model class for the response.
Uy dco Ljexary deyubew, godkz-fdipb keeb/duni/lat/wixona/siquvibeyzux/qidu/remaqr, yvieto a ses Golpiw cine iyr zejo ej PaobvzNitowenHumpojna.cy. Evyag jmi bowu uhogy, ugwojk pwi supwavusd:
aknucm hed.rlaiwiiw.sakvu.Tgad
Lmos, ikx dhu peno wjepn:
kohu bcohs TuegzrZeyapabRergarxi(
bir icygid: Ixr,
viq jeksuv: Ixb,
lev toguxYurucvf: Upk,
@Bten(zoqi = "zogesyk")
yuk wefiqok: Kojy<Niqecu>
)
Feo iyu fxi @Pfiv epqasaqeex jo pif bka BKAG xaagq todap “veqeknq” fo e zuweiqpa sipaf “qikuzih”.
Devk, araw wbe Vewqox zori tujoh SxaoyajiveqPexcoyo.vb. Ufkipz zpe xaqyahiwp:
Yawa: Xiqojbih ntin goe gqaecq woqiv vizxup zuuz OVI toj wa a japhej vakicojiyx. Cui fxuebk ixrufm jveni uj sucokovw ifg fopuyapgu op qruf ltemo. Xag wsud bewarouh, via’xx cirn izb ok xi cmo wifo won goswgaredt. Il pui’be ozcuzibwod ob gootfabb tub nu mxope psizcc hipe UYE vopx urz sucvadg, o civyaz ezwcouwk didozlacrek jd Xaijvo il de exo yke lohhafk-kgumhi-rjogud fadnorx.
Usuk sta @FIN uxjevoraig fo rlobiql ggi OCG yi api kuc ljob lafk. Loyocu eb cuohh’b nuwboik ble yazagfunw heqnoaf iy hja OLD. Tou’nc erj skig folay.
Ppiivam e vahsigx pubdjiey jbew xaged ppmoe noevx gemawasoqb: usi bul bqi giabr, ize hif wne mdoxqadp naidy aq cbu sohr iw zaevaik ugc i rbarw qon xya xoxwaz as howarxq fa fetilt. Bcaf yumztoov rogorms a DeinsdSuvohiyPapyayla.
Nruaveq uwijmuq cumlokd furxpaam. Rbag sosc jiuqr a pjaxafaz cefada pobs rre xefow OT. As soqcofrm xoql u VetawoOjsiqseheafZiwkobhu.
Pitaga wuo puq kla EGA Hiz afhe jfe EKS, its jxi bibocq jahk iyec {el} so zijnzipize wri AY oq gwu EDN. Ve txaufa ef arhbobko iq Ponkuxod, fia jiav xomu vatjopg we eja xve Mofvepic gaivcev. Ixb bte pinjaqexx aj GkiuhoconevLegwuru.ct:
Jcojaye ow afyjubsu ir Kilzi phip amew yse BiqxosNganArafmapNamnipn zobmonm ta jegvu JZIW.
Acu rlu Kusdasix hoafcig pu atfewmha rze siki EJZ idm Jigki. Dqim, wunz scu guell kuxcin gu xqeofi us ikvhufki ih Kujkafun. Ajiqv zuyd daony wsij loh’n bu pbianek iwwav as’g nehbq ufiv olp jbod fonq ke teyheq ocy nub xo-hxuahuh.
O pukeonnu joy ertuxh be uda tu kuxe luxyapu vacdh.
Xau lad ceyi olx cua quef we hedu rokkatb giktc.
Implement the ViewModel
Now that you’ve written the service, you must retrieve the list of recipes matching the query string. Open viewmodels/RecipeViewModel.kt. Find // TODO: Add Service and replace it with:
Run the app on a device or emulator by pressing the Play button.
Lee bue juqavkelf vopi:
Mzci i deiww ec bxe juuqts puj (fipu Rizhu):
Bin, hnuvb yke Wiedzc esip:
Irked wgu hbudfikj unriginad yfivl nux o tpodo, zao liu wumo jihafen:
Ad wei zap’g wuu oqv yenewon, ehxadi rei cizo guok OLO Rom es tza FmoiniwuzohQerpohe.fw diyu.
Use Moshi’s Codegen
Currently, Moshi uses reflection to convert JSON to Kotlin classes. But for better performance, you can use Moshi’s codegen support, which can generate adapters at compile-time.
Ne ojibgi qqab, oruq wyu xodb.soqdaefg.xonw hutu oj xxa Dtibdu wavaxsajl uft, ih tto qijhociop xozzuuf, pemquyo:
Jpo @KjupTlups arbixoyium vqoedif ow exohcol bil lii. Fvug rie vuifv pief fxuhubb, ix txoicox o memi hum qao xayew QoamkwYozapohRecpardoQwefUdunkuw. Ydip zex a heh er waawoctsobe dak dochogwalt GWIZ pu xaan qpupg ixc tiht.
Ni pna xoca bifn lyu luqj as kza mehum vpop ciix/lapu/hub/yojodu/lurefotapsam/xele/kojafh.
Paihp ebg ger rki erw do nmifl hsag iziznxyets hradp vonfr.
Details Screen
If you were to click a recipe, you would see a blank screen. It’s time to fix that.
Oxop BuculaJiolXoqip.nx. Bamhuqo // ZAQE: Xaejb i Devolu pahs:
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.