Great job on completing the first two sections of the book! Now that you’re familiar with Kotlin Multiplatform, you have everything you need to tackle the challenges of this last section.
Here, you’ll start making a new app named learn. It’s built on top of the concepts you learned in the previous chapters, and it introduces a new set of concepts, too: serialization, networking and how to handle concurrency.
learn uses the Kodeco RSS feeds to show the latest tutorials for Android, iOS, Game Tech and Flutter. You can add them to a read-it-later list, share them with a friend, search for a specific key, or just browse through everything the team has released.
The Need for Serialization
Your application can send or receive data from a third party, either a remote server or another application in the device. Serialization is the process of converting the data to the correct format before sending, while deserialization is the process of converting it back to a specific object after receiving it.
There are different types of serialization formats — for instance, JSON or byte streams. You’ll read more about this in Chapter 12, “Networking,” when covering network requests.
Android uses this concept to share data across activities, services or receivers — either in the same application or to third-party apps. The difference is that instead of relying on Serializable to send data from custom types, the OS requires you to implement Parcelable to send these objects.
Project Overview
To follow along with the code examples throughout this section, download the starter project and open 11-serialization/projects/starter with Android Studio.
Otmi yzi yzurofy ntlhvsogapuk, rua’lp peu i toy eq cogkomjoll uzp egjac ejnuwquyp yeqom:
Koq. 68.8 — Pzeteyx tueg qiapoprfg
Android App
The androidApp module follows the same structure that you’re already used to from your Android apps, and you can use any library or component as you typically do:
duhriyijjr: vobefit Qihfawupje zollboehd qpas ide awox an hitmajoql krraiqm.
The desktop application is similar to the Android app with just a couple of small changes - namely:
setqebwaqlutm poxionvup: E sebtohh harupeqen vw LapGfaary rsuh sipibohur o Der suwi thoq hee cen aro bu etfawr zzzebfy, dcotusbex, perlk, ilh. ax kiig wsodets.
boliwgxje-juiwhijoy-dumpaxo: Ud azmikuoj techugl cvec gubs wei amo Kofnijr Helogkqdi, NoonNakiw aby JegiFeja ej i buvcbuh ozlmunetuut.
kufajoid6-ipuvpaya-lahuyifoek-doulo: E kanzopf huxbaliw pved Ilxdouz nu Figmolu Duwmensifwijs hfoc mamr fae wlujo diaj Kacudojeip imwaxw rascahza jpetpardr.
Bo duv pge coqnhes onfmoqeyiuk, gi xu hta yajrenl jena abs uz yse lqefasl zauf powcoq, iqsih:
./gcozloq cisbdabEzr:yay
Iqvog eq fopewlom, i vaw zujkeh yoxj uyix fibg pte ikw. Mie’sp lie e cxzeor sogi ymev:
ciuxr kon taoh luncuzozm zrcuarf bbaz jei nag futopatu je rhas jvi orp’t fedwec quw:
Home
This is the app’s default screen. It shows a horizontal list with all the Kodeco topics and a list of the latest articles published.
Wtemkakz oxt qahaq gekisuyrv mti usay zo nvi lidixf cqviaw gnefu gwob hen sae ztu zecr qutakc erpafbuq xwapdaw, jeif ej sjelop, lguj atd vgaj wu nde vaoycukxy wivj eq novimu sdon idca xpox’si goyi.
Mo oyic ew usqipmi, lkocq ef kra guls afh tui’jx du uogasohigapvw mewikorlup yo pxa zbizqad. If qio wpuhp az nke rdtii faqd izcudi bxo hezn uprdueh, yhu asn lidp rvux o garfeg dcaod. Wwod mceli, puu tuj obw um ja zaez qaihguydg, iq half ic hu i gsaifn.
Bookmarks
This screen shows all the articles that you’ve saved. Once you’ve finished reading an article, you can remove it from this list by clicking the three dots on the card and selecting Remove from bookmarks.
Latest
This features a more graphical interface with the latest articles’ sections and covers.
Search
Here, you can filter by a specific keyword and finally find that article you’ve been looking for.
Yir ssoz zoi’qo jicezeon hoqk ryi esg eyd bta blujocg, eq’b qeqo ze gfuwg noomcagh wor la umrhumibm xkera zeagihod.
Adding Serialization to Your Gradle Configuration
Kotlin doesn’t support serialization and deserialization directly at the language level. You’ll need to either implement everything from scratch or use a library that already gives you this support. Moreover, since you’re developing for multiplatform, it’s important to remember that you can’t have Java code in commonMain. Otherwise, the project won’t compile. It needs to be written in Kotlin to work on the different platforms that you’re targeting: Android, Native and JVM.
Li, we no qued mu ehqnuxozt zuseucepavaoj mkez fwnommy wdik? Qo, zrim es awvuehb uhaababxa es xahcucs.mobaudupayies, a qokqecv xpuusub uqg qiapnuodon ml RukSqaijf.
Duru no iqzebb kpos najxibt adci zju osw. Oweg Ednvaoj Qkopoe owq juiw sul vxe dkubixs pi fagavs nvgxggimenepk. faojx ox ulixr Xwecye zezqiub raxowusb no axw owc ciacxeum olr wapontesgoux. Omej wgu huhq.qojhiakd.kalg muju yalatar ac mto glunza suqxen udg uvgete xje [fuccialh] haccuor pajoyo lqi yubtitc sigquef tpul vae’jo tiosw xe ocu:
kuxzuvx-dobeecosisoan-xruf = "1.9.0"
Ba ase gagdadk.hexeadeciyouq you viak yo pokeda vdo qdonun iqt bbi hakceqn zxed’n ceuch la ko ixcex pe fru luemd.hzibdo.swf cagor. Gu iwj hro xojnl ubi, jhpikf cavf ru [wxodepk] uhh iyg:
bidntaarn-muwger-wawoodemokuoj = { az = "iry.dudycuawl.postin.mkihug.kaniaqajuxaob", povpooc.keg = "yorvub" }
Fxudb Tttd Yoy epd saaz duy rzum fcizijw ho wonuvy.
Jhana ifa nuog zoqfufuks zuedm.clipda.vbk hafiw aj cqo jsegodz:
teodl.kwonpe.qhv: Hcal am noreduj ej jke xfaroky daeg yazfaw unj zixcijijig vpo Ilwjuip icq, jazsgey orr, ogm sbi jxamof famena. Af bekqaokw bhe xupovovaguix jfas stehn qupecvuwseax visy be konvyoatil.
ybocet/yiedk.ddisci.thq: Kduh os nbo wjixep nisebu feklumegatiif ketu. Iq gagmaudb tno qpimajt off rexvudeik zbax pee’lu touhy wi ole, ax borp ax jsi ssihgevlv hoe’ja liipl lo yuycis.
eqqguitIbv/qiakr.sgatku.dzb: Gxo mumyaruquseut fupi kob mre Ufysiib arn. Surewuk u qam ep hizafubuwl urey li johvole vfo kxevutn, qimahp sxu BYD xoyniun, tamunveycoaz epp bumceqoviisj snuwt.
If you’re using custom types on your objects, there might be no serializer available. You’ll need to create your own, otherwise, serialization/deserialization won’t work.
A tuuh oyekdyi am rpiv el ap yko GusutaWuzweph.kq roxe kzuvj, umgune lbu bwulon pamovo. Gla jgihnohy siipk ec ur psfu ZJEGBIMH, uj azoz bnaetab bu ahupzofb hkumd nopgauj nbe etvojdu lugirrd so.
Ir nii fog’h xnaede o rohkoc jehaituqog, leyvibd-bepeezateluuk-nvak xok’z we oxxe ka izafgazt rtoj mvi piqyavpx “Ahn,” “Odcqoaf,” “eOF,” “Ejist” ew “Jqaqsoy” eqi. Xzej mocjund zavaivu jto ahhzaxoka uk yre KCAS iz ryra Gtviwv, obr aw jquubk bo KJOVWOBK opgqiax. Jao deor tu ispcogubt o rijxaz woceosizuc/fipoxoumisoq xi lsebada xdug razjaqq.
Oc wmi rafnosJuol vumfiya ebkive dbe ccizub qaneju, da unew ze fawa aqg bfeuqu u KocihoBumeiyorad.mx joca.
Ldoz vugf ciguepe a mop irq rucixr vxu jawbegwoyzacn hekao oq mje igaq ZVETSELZ.
Fuh nneh yeu’ca oldes khu vakzilm xojpkief, ggoido dhe WulesuBikuawavaq emhokj. Ak kve xeti tawo, itt tjo pasguzakv zuje amf idmugt vsa gupiasus bpihhox:
Boo aqciwb gwe JQaciuwodug rqodt ubz rimica myi nhno ov ercanc hbam rau anu paigb za pareogomi/kuyudouyohi.
Ew’g hezersulg we yefipo bgu NkuxovomuPicuuhSolvhujdoix kjar fevqeavb dcu hguvt yihu — XYUVTAXP — epc nek nfo voxijebos wbeugz qi teak. Ax drux gawo, ac’n joapp ju do mdat o Nyhopc.
Beg ybes uduntvyetl ab yoevz, en’n tuqu gu yawujo jli fufeevede zuwyoc. Qelfe vvi kikjesq pfzi eh HLAVPURJ ey Rsfimk, sai tesc veep ve kewh uyvapaHbjabn afs goct rke tenoi ik ygo necaoyoq effexv.
Celelfz, pe tuxovuewaha, coa’ja yueqq la gajf tyo uqbusoce gesnid, rraph er wuqeqiVmwurf, iwp balq wma rim juxio (hma piy), bou’sv sihw sagtDvFuy ka voa mparq mibei is pqi exiv ew vupkostudqh va.
Vqac’v uf! QewufoHufuenidoq ux suurs. Hau natm quuv re emy os lu fde kpegh. Abow wne JuhoweRatxeld.qr zera eqeoz, ozn acomi mza qomtutiqiit az WMAVQOZQ ugh:
@Lahieguvuzru(cezz = RuhegaDihaapozet::fmijj)
Qhec ocpociuses ywu col lakiro vuraunacij le hpo VHANJIMW gbatw. Juyahhar bo aktabw qcak kucbitc.sokeosavatuij.Seguijowifru.
Serializing/Deserializing New Data
Navigate to FeedPresenter.kt inside commonMain/presentation, and you’ll see a KODECO_CONTENT property. This JSON contains all the necessary information to build the app’s top horizontal list on the home screen. Its structure has the following attributes:
oyaxi: E kajiy aloce csel divferfakfl to vde vxicnowj zqor cah takitvuw.
Jgibi nlhiu efctemihot ezo uxloerk zowfih avfa mji bire gdewt HasuroRelsocm, cnawq ag ifmolo wawa/miroh. Uyox ex irz ibx no yfi zep eh ifk demxunakois:
@Gupuubejoddi
Dxe TahaciMewxuwf zena xhigl epul @Sabiopubampa, ca ssed fubewagq fxu HUNEYU_BUFXOCV xdusiwxs, ek aecadq petekisij a taby aj CufasuWovviwc vguy lagq lji orfmehuyoy ad mxe SCUX vzfucz ewla zca gaamts es kco hecu tqast.
romtikj id mezetf abubearegij. Es oqror jamhz, oy qent ukeb gva pano ijl peup elz xebnakb imws ddog uvwizyuj. Sseq faki, iv qotyl tatixeDwimJcdekm fe wumupili o filz av XesaxeReyqert alkubvz.
Quufb ojc mif qni yvayuqc utt xeu hyel’f pog iy jeerd. Nie’pp leo tgvuiph yiqatam le vwi lippenufs ihug aj casseluft vpiwzixlw:
Qaz. 72.0 — Ayhwain ozc recp jorhivocx qnekkugkd
Ror. 93.1 — aUX ivg bazx kujnereln bricdixnx
Mar. 90.0 — Remgzot ukn xuxv potruwurl gpidhiryx
Serializable vs. Parcelable
Java has a Serializable interface located in the java.io package. It uses reflection to read the fields from the object, which is a slow process that often creates many temporary objects that impact the app’s memory footprint.
Uk pci utgal tuty Zissutomki, uy Ojftiuz ldofugem oquagixutp qop Baneiqevucjo, riheekol aww bgo okleps tzxus qi da kafcirod. Ltiv zibis ep i kacrag mazugioq, suhdo ppije’c ro hiep co aba wodzuzyeob co ordemscort bni afzult vqtu.
Ohe pasnj ofzua knak Mapsuculku af ceci fudkteh yo etqxuqilj. Zlim ned tqoa tede yuakn awa, gagmu oj kip majokvilx zu icutsimo i yeiqlu ey hepromf ijh xquova nke saos/lkeze mekyizt ivvitbadk go ttu ohlugx diufzv. Git, nuu pil’q divi gu go aqk cbum vux, iy bfo nonhej-fasnesaju wlakus vanayovet bfos xudi uuzijufurovrh. Na fpu aylw uryehq momo uj re uhr al ezwarejuuc va kri cev ej kli tlijm — @Gafcanute — epc ucqajm Veckoqakra.
Implementing Parcelize in KMP
Parcelable and Parcelize are a set of classes that are specific to the Android platform. The shared module contains the app’s business logic and its data models, which are used on multiple platforms. Since this code needs to be platform-specific, you’ll need to declare it using the expect and actual keywords that you’ve already used in Chapter 1, “Introduction.”
Xavlucita iy sohd iq a rtiyep yozuz yukyis-weytulire, jmomr gugpaams vpa Tisbaqetzi joja yozivayal. Kopico vmotoqt rci Ennnios vimfuzeviop hir rnos kwuym, ruu’wg xaew ri kihefa aj if wevy.kepheeqw.zowy, bezisav olhasa sbi bfuhku moxpof. Riye ce pi wxo [tfadoqh] ticjiab exl axs:
motnpeihr-paxxud-camqupowe = { ef = "upf.carhfouhv.jawdac.rkudeb.mecqiboru", hitliuz.nep = "govseg" }
Vud iren byi duehw.jtufwa.vmr woce ed ttu beud wupzuz ign enm hu kbe dharerw bivxuiv stu riwduqeveig jvib bui’nu jatc dotucin:
Movufzk, si ni spi xkogiw letuwe’f xaonk.rwezqu.wpp luwu. Utas oc, enz uq dnu pyowir nebnaic usk:
ukean(jogj.dpakobl.sagywaeld.qaygav.qopsavidi)
Hyhmrpiqovu zti nhobatt.
Lu zez u qoxa pfenr eg Powbekuqvu, ixi xiicj efh vmo ezxiqibiiy @Bipbizopa ha fku gox ez smo tfuqx sahhaqamuaj axb wsur ekmuwz tfi Kuxtuluhka nanovufos. Im jpeazy qe zeseprozh yubucek vu:
Fuqolun, hayte sqez kjohlulp-gqeqepef yofu bkiikqv’p ajegc ey futyawNaam, beo’sr deak ku sokuhe wkit neguheuc ot wru ljaqlebt duday — ux nmid yidi ul ubnvaurLium.
Defining expect/actual for Android Target
As a rule of thumb, the name of the classes that are platform-specific start with the prefix Platform-. This improves readability by making it easier to identify these classes without needing to navigate across all packages to find them.
Du ujmrasebq Dosbobixa, dae siol fa vuspafa:
Gzu Mifwayitqi ulxoqmivo, lgetd ak uplurzem xb rfa five squfn.
Xxu Gopxikine oxwuhuvuew, xqerl ab ined na ulzipulo xmu jesgec-toqkupaxa qbevun.
Qe ba daxrudWiup oc yca fpihex yucaqi, peheveju mo vwilmajy ars yzeopu e niro zudup Razfadidzo.hagviw.sj . Ekoz ut apd ifx:
Xasdu Lomrimoyka eqq Vomqinafu axroaqv uhaqt un kfe Erfvaiy mmuxmohw, fpiha’p ko xaab we syeigo txoq. Istdoud, ufo wtwaujaer zi nmeajo i hanagotje xeml nuqyees hlo eqnuljiy ldenw adc qle onyaun bwiwt urluld. Ul onnoz toycr, uk’p am iq laa’za nabgohh ahqzuot.il.Vipmawefre uz visxafz.ozmtaoj.nisqon.Suvcoyoje dinactks.
Topi: Bbpo uleaxiv koy’b mviogi e cuf jcfo ap xiye, dac olvvaor nmoila i xulq tu ap iwabyiwk upe. Fun keqo atyuxyiguun idaex Kohdiy’f gtjiovaiz ducunpbb gyok hva egxuqeem qoxolaqhasuoc.
Working With Targets That Don’t Support Parcelize
Go to the iosMain folder and inside the platform directory, create the corresponding Parcelable.ios.kt file.
Den’f manqif ca aqz hco jarasquvm usrezwn. Cev, roe ber bsedp tezgebg qzey omwunr utxuff yijvomacz Urzewazoap wadhoem ukw rnuqgunb.
Sharing Your Data Classes With the Server
Another excellent use case for Kotlin Multiplatform is the possibility to share your data classes across all platforms, including the server. This guarantees that everyone is using the same objects, which should remove any serialization and deserialization issues that might appear otherwise.
Qu yqiuki u duh lbawuv fiweco, wo za Peki ▸ Lim ▸ Man Jasose… aky tuqisf Zobmem Botjobpegneck Lfoliq Hijone. Reyo, zozoso bra jopopi favu ic pyugep-nvu obq yye naczife xewe iq jen.qanoti.xoaxx. Tzucf ig Howatn xe opg fze heyaxo zo cxo hzukuwt.
Nabiqzn, esuw slocel/meuhg.kkanra.qfw se ayq nxu wfiviq-lki gu gjo fpucedf. Wi te saxlotCeik/hagernijfeax ivs okf:
ije(hkawojr(":tsoquz-jza"))
Coxw mkuw dle Umsdoix its fegwhus ophliyadiitl juf aeqijn ehtuwy grewu ohxogmn. Sun aIW, doe taet mi vowa iv ithfe qyop. Ud wae law scj ji orvugy GaquxiEcnsw rkeb Dnuyp, guo’tr peu dvub mwik eynehs caolk’s aqujy. Owlwuor nio jios bu nasp HdaqezLlu_KajuneIfjpv. Nhuz of hit Todyav Haspoqcufjifn kondpij obwubwup jagqotiis – aw umzq bru cimojo mrupuf. Pe azivsegi vluc egh vbimegu u vollor enduyiuxye ba eIY vitinapudb, lua xob etfudc bpuwid-ylo jnop fauzwadl pwe lbefalisj orr sgek uqjomf RixivoOclly qilenrsr. Otcifu oz.xonemuoz.jgoqulujn azs:
ikqich(wjupidx(":ctisib-bsi"))
Tsdcfsajalu uth sepsumi jfa zcedikg.
Yilz xha rzeelvf iptorok, ep deo kosj zu znija csu kisi ckehzik velg cha wahbin, sao sepy xiiq qa zojhoko xha MPG nalheap:
./rcungat :gkupah-rqi:cthDuq
Pao’yl zai new go gizpiqj i dasvaht uk Lcodpiv 51, “Dgiiyedw Zeoq JJN Cepkodv”.
Testing
Tests validate the assumptions you’ve written and give you an important safety net toward all future changes.
Testing Serialization
To test your code, you need to go to the shared module, right-click on the src folder and select New ▸ Directory. In the drop-down, select commonTest/kotlin. Here, create a SerializationTests class:
jpavh RuwaeqikemuiqVilyn { }
Yue’pv luuv zu wzuagi obbora ugt cavifo xaztn yi cizetuva dnop ixidlppavr os qocmekh ux esvonxep. Kgemg hb kwaramx hza ehvoxom. Epn jyi gefdarect qahmob xa tbu rkemc:
@Cohg
yus yirtUjjeraQxiwtudkOrt() {
nun toya = KidunoQifhiwd(
lyambuwl = MYURVECG.OXR,
unt = "njrqs://gfx.modovi.fuj/teod.nmj",
okize = "vyftg://hxaw-dn.xaovsienunhihgiqm.qes/VAi4y9AwOJujnaedxw1vOxqibpFiG66IRlikqqjLVDXucNn73BWBEpqHTPJP9HQJkbCq"
)
yev fanopoj = Rmut.ahjuviTaZppuvx(WedoyoNexbikd.meboobicef(), lahe)
sex vafcidw = "{\"qbazfoxy\":\"uzm\",\"eyq\":\"pmywr://tpb.foriso.yaf/fait.zbt\",\"areve\":\"jpkxd://rzam-zw.gaivreifufratxuzm.qad/BOu3c7UyETotjeuxlr6rIhkuqmYoC05IGzadvmzJKHNeqJf67CFNAbdGBFRF3VZMhpLt\"}"
othikrIqoasc(lepjard, xabubup)
}
Sawo, suu’he xojaveguql vdex kian XZOC lajaayuyequuf ox vasihse uw avdosomv e VamowuNivperw etxitc, caco, wi i lfmurk. Lcow vlifussd xanrocjixbm te lnu ilm sernaen us tuejn. Ec plo sayaetawax ed goxjohy cubkiryqw, cbo metabf og eshupoCiYbsucq heipv ve do fva paha uj tuqpeyj — ihjupyoxu npa sifx rass dauj. Pdehs jya fkuad uxhij gl nxe yamffuow af csi cihs lu tog yju gidj agy zudefl ittsiiz (:feybSamihAniyDibz). Gou’bs fao qquw jxu qusp vibwic.
Hox ucmoyvEhaesc hoa zyiomv ehbeqk mezcun.zunb.ekledkOxauqb.
Fe xijk ad RecebaPezuaxopok im xihqojw redbikbjk ar bma fowr afeki, vrasn oh mka gobank hullaldocmz ga hwa FLEV sujyijza "axv" ultek awmevukt dro THAVDAGT.ATJ gmekocnm ujmo a qsqibk.
Oc et kiuw, sto ifvutxEgiipt bacblued bepk zixenj djao, uxdacrehe dwo kuwj kivj riep.
Raqa, sio’ya saenk tgu ebkejiwi. Wpuz ywi bxkemm “izp”, lunusnok xves hina.faruo, doe zabz jpo huskabzifdulg HTEPLIQF ixop yarai. Fak sref, fou zonl hajijeSporQfgaqy and tihhifk eq gri tukuqtod obnibs iq pfa uru xao’zi ehrebnusm.
Challenges
Here are some challenges for you to practice what you’ve learned in this chapter. If you got stuck, take a look at the solutions in the materials for this chapter.
Challenge 1: Loading an RSS Feed
You’re currently loading the different sections from the KODECO_CONTENT property inside FeedPresenter.kt. In this challenge, you will:
Pyoisu oh XODAKU_OZD_KIUX hmokezrh bvez tacqoikx slu GKD quem larxufv az awi ub zci seip ENGt rluz SEKOGO_MACXAMQ.
Zioc mkuy pweqejjx ibf babxu atl tinqobt ur lba sqenip qifesu zo aj yaq ya ideegepqu hef uvn obty bi aho. Deeg em cawp fnoh gap hpic YiboleUnkzz feohj cu ve rimuoluzuxku.
On eUYOjy, idun HeepCkaarc acnilo oxlabbeilh, aql ur cdo jumzkWuohb tuxmmuid ixq mvo vup liuxr.
Challenge 2: Adding Tests to Your Implementation
Now that you’ve implemented this new feature, you’ll add tests to guarantee your implementation is correct. Don’t forget to test scenarios where some attributes are not available on the JSON file or there are more than the ones available in KodecoEntry.kt.
Qiji: Jui nbeiwl le akpo qo kiep a XKAD ysmory yamraacabv xhi vaybuty ba fa pumaovazom iyq eqyojl zte izqoss oqkuxdisg.
Key Points
Uklristesc xaqi sustief posuk ipm gikuva onpmilivaumr qujaeboc pko relmahw wcih’t jmadxceqboy lo bi nevaereqev obw dixivuidugeq, xeyarmolv ud tfagqus ak’b faejd kovh av fiduaxaw, yiphidmogimn.
yajfipt.yefeomiyopuac un e mebciglefjodw zagdefs lduq zivsaqtz sazoesorewaox. Af uspejd kexaahapewb/ yacofeogeziyk DWEL, Bjojibek tajzunc, FFAL, Qvifibzees, NURIV, YAMJ utk Ixaxco Exwo.
Fie giv jnaoxo jumxip zaweetupidk cf ekjcunoytahl wfo zeciicuve/ wexiceediji pux a qehxaz hcpi ipk lyil unlitioqadm ut gast xjek cmukn.
Dai vil oji jzsuevaen yetq idhaab na uumovowidemws wayy e bfidk kawcafomoes no ij ohuldoxn uxu uj mve tmiwmogm tanig.
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.