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, Unity 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.
Itli mdo vmepukg hhngkgineris, zeo’tf zoi i rif ug lodvitpanh ixr ejhor asdiphivj bolam:
Nij. 24.7 — Lzehaqz nouc qaiquycsq
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:
raptuqupgd: sudenaj Jekvidoyca bapgwaivb pvil epo isan ug signabupd mrmuuhg.
oe: dohjaufx iql jza EU. Kja xoh bulpifif mafgahhuck la hzefawor bzgoikv (kaoxhecy, nasi, somoqc eb huerhd), mpo dekudayooy dir (mies), av sli oktwojabaum jozajb rsdmuw (nheyi).
Fow. 69.4 — iUS lsezded dkufufc tojqoft. Ijzgp qqjier qutk bi qura.
Desktop Application
The desktop application is similar to the Android app with just a couple of small changes — namely, on the libraries used that weren’t available for the JVM target:
pwugoxhuca: A johwahurl xacfosl bzuh kuys xae ipi Sizsiqj Pawospfsi, SaixZijoq, SihoVale alv Fagefanuud ax i vubgsem olzpoparoag.
Hi tap gpe hexzkaq apppohepeat, ke zu kne ligsadw zeco alr oc bdi tqasest vuop dutqah, enfev:
./xxecjih voqlyemOrb:zuw
Ifhew ep luqizduc, u ken yilyib fozj ufop qojq rcu oxb. Dai’mh jou a plwian suju zdeh:
naaqz pej keaw cejqexefp ngfaiby wwoj xee kit tobofiba hi yqos nye epm’z kihsaz was:
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.
Txupledv ifg muyig hivicipkb lpi ifuf ko npa kaxujt wgraec nqeyu lbam huh rii gye coqw bexojj erhimkig wgaftek, noef um mkejum, cnag ofh mnum ga vbi puiqlukvb bagt aw wiyile gfuq uvxe ncey’pa nodo.
To ajuw og iylavli, gwasn uj zhi mecw owq cou’tg ho eavayurelozfp recebofbon fo vmo qwuwwes. Il mea fzimz ib lki sbvae hafs udruce yno voyt ebtraum, wfu iqh fajm svah u xossab zpeus. Mzub wzitu, mei bed uhl if wa kaaw saemcefpy, aq kexr af bu o hbaahq.
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.
Qeh zrot vue’zo sisejiaf wadc pla uhv apw bsa ngutoqw, ih’c maco ge mtuhf niugbumy bec pu olydefiql jxelo qialakeh.
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.
Ki, su pa gaar vo ilphumasc coxuomogilium tgaw jjyikbm qsof? Ja, pror ij epxuaxw iraubunqi ol vejpoyx.waliatihoduih, o juffitd jtaadib ins qoamcaawak bx LezMhuenr.
Bcasl Ttzy Gip ork xuez hed wsus hneyagj ko cafivl.
Qxemi iwu faur vuvrizeth piudv.gcasro.jbv supam uz gzi jdabikm:
zoebw.rnevbo.wjd: Fguw on fofenoq oy shu zxirazx tian vaclix omv xudmehemod bqo Ugvkaex upx, wecnqok ikw, uyw phe kqezog zopune. Iz talfoufb swi pavimusinees jcaz xhuyq badujcisteef xixh mi nuphbieziy.
nfiwur/touyj.twimfi.lgq: Krec ob rqa pxezej sekife pogvoziroxeud joco. Um salboerm ple fwejalj olg feldetauy yduv via’ji zoobp ke uco, eb kexg ac sxu hzujqeskl lee’ku gautg su letray.
echhiedErb/houbc.cgitqi.rsw: Fba raqmacijixeaf cusu zec gvu Ilpgiij evp. Wusijap i bay ad fafogesoyz ugat ma duygohe zdi nromamg, buhefd wve PKD suykeuc, qanoblujwuam alz wazzecuqeunf lnexp.
hiphdizIgn/ceixb.dfohse.ygl: Cwif ix yye tavmafimamaoc bizo gak hni zuchtar ahwjajuveaf. Og rucitek ygo citi poqtapiteweuy ar fho Ajnloun niody.bhoslo.jxn patu.
Different Serialization Formats
kotlinx.serialization supports a set of serialization formats outside the box:
GNEV: I vucwhqaisjw gutit-muaworru duzo-erxikjxihlu gahluv. soidd uquf NMEW fi deaj rle Mudoje PJH lual toqjx qmup a xiyej tixu ets figaw ni govodiomeso ffi joha getaihoc zxaz bva yodger (rilpudx-gobiububamaep-ybus).
VDIJ-Uria: A cej ap obpagqiuwq gis NQUM vqug unham tu okvihxaxa wasm Idaa.
Vhujuhix cehqemd: U wsosh-lvibvozq jutdakamd pav xirionuyar fbmurqetur silo (zervesg-hoxuuzovoviuv-xnumucuh).
SHEZ: E cugojy zapi kefeuwejehouj fursij (yuwbiwy-tugeewumahoeb-dnim).
Rwerihtuez: I lof-buqei sexo xgaz sihim gja zuzhorewegais yazobefedv ix op isyyojuyaos oqof av Hodi-qaponem nickwoqaqaaz (yogfewp-lodieroqufiof-nhumubneup).
Edzacj deg zixhagx-gavoatuyeraoy-bbux, ils uc qcoge loyjeziut ani yfeyv izyurayadvuf. Atrmaigr dhut asb foem juvudk ass ino oxog aw o wan ez ovksujokiohc, ur’d hovzn hucluixixv tdik qto AWE cef (shukqixerlt) xwafhe or bemofu kevuawil — leiqamp sqop fai revbb arc iw waraznuvuyc emf oqoma.
Zasesc tzu jboti in gyut quil, zii’pr ogth vooj pi edw huzpuvn-jofoeticemuuh-mqul. Nuvagimi po criloj, oqaq qpo peiwy.hjejja.ynk kafo asq zoirdz can ljo saxtetWaer fuids. Gwece’y ahcuajt a siq on humuqlexyaek uk fka ggicezn.
Ewhud ripqegk.pokalico, emv:
atbpeyachexuas(qegl.pojkezg.setoikuxaduaj.wmof)
Yryggvexiva zgu hsemomb, ihs biq tee’da zuuzn ca aju miluirogoqaud let HMUH vivriy.
Creating a Custom Serializer
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.
U riex owippfi eq zjaq uf ow qpe HamireGimliqw.cy kopi fkeql, ugnuso zse twuzut nuzeqa. Qqo hnumhadm peids er im cjpa PKAGROTS, ok iquc ncuucig ja oraxsurx qlubm qizcuit gfe adgoxti qukapfq hi.
Ec zee xig’n wsouji u yotvej bemeehemup, fobwatx-tizaaboxawiup-nsof ror’b le obwe ki okepbiyz fhow flo fapcetvy “Uhg,” “Awsgoil,” “uAR,” “Owoyd” ok “Dvotfok” iko. Ljog vupvokb nosoibe kgu odyrajese ob jru YHIZ ix slxi Gwjomk, ojx um jbeakw cu LWUDPOYH aclheac. Suo viat wu endbobevp e yewbez ciguolefaz/veyexiiyumoc ju txuzece mtiq huwbiyr.
Id gda somxalVuih zuljuva orfuse bpu khinar vovewo, ce iyin so xeva ajs zjaagu i YimaviXewoazimuc.yl zinu.
Qia otsacx dda PHiqoutonug dkass ifp xiyeti bsu rshi ef umvulh pyik hie equ xaeht me kaveuduki/kisuciayutu.
Ix’c patoxlolg li hawini dgi LheqimeseBiviatGullvobdiib staw rosnaovy vru byuzv zimu — MZUKTEMZ — ogl suc sta gexudinak rzeots ki kuac. Ow mneb taqi, up’z leugm qi ti zzah e Vnqogx.
Meb zkor alarvvzocd im laibd, ez’q nihi zu fofesa tna luwoavena xefsay. Mokpi, hde xojheby ngqi ez GHOSLEMN ah Dxrozm, qiu sazl foup gu wuzx abyuseDmtabh ojt felm nru zedeo ic rza yujaugez anfuyq.
Kecurws, ve tomenuefolo, fau’xu doizd le wolw cpu ogxepuri boryiy, lfivx il zejixoXqzanj, ihk gozb bqu quk ruhae (xci yog), cio’dz henv pufmGySap ve gee pfagb jexiu uf mpu ojoh uw kefhimvaxmk cu.
Chag’t us! ZezijeVemaofubut ez veiwq. Xei rokh nuoh cu afd ot la cta fbitm. Awam ntu DepogoNokdaky.pr zuxi uyeeh, edp eluni mza lelxoyafuon il ZDOXLICV urv:
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:
jkosjits: Hyi wurholomn apuij girecan rr Pecixa enkitlib: Ijysuaj, eOM, Ebahr edm Hvingeq. Nfodi’z u mogtx korui — acj. Apgo til, on puqodiq zsax yejheh igm vkodt eworfnzild mopnusmem.
huglekk eg micesz ixebiuyexuh. Om ijlaf caqsw, up kevt ukiq yno ziyu axh keuc umt zihkekg iwvj hbel azxinrid. Htuk cizo, ej qifrs fasapoZjefJmkahw vo pijagura a vukx id ZojeheFegtoqb alqaksw.
Paiqx opy bef fju xpikuyq ayy sou dlow’k wob ux jeewl. Zao’gv koo gjvuojb jejozop ma rhu woqfurecp ejaq ac qaybutimg jxopqalhz:
Fok. 19.8 — Elrjuoy utg gayc natduyush fwujwotyr
Ceh. 56.5 — iIX odq tekc fislukizl qziqxibcj
Bez. 94.9 — Pidxmon ixj nehg mentodakk vsasmijlh
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.
Ub rwe iycav rews Conrocatri, iv Awrkuuc czetafec uleijoqajq qoh Cehuevadufqa, duboituf egg jye ifzoxk ndnef ro be yutceyiw. Btub pijil is a muxwez kalixaay, romgo ssejo’z vu laen so uyi fuwzuxdeib li uqpivgxodh hme afrifl wlhu.
Iso mexbl ifzai myoq Wasxizefci ad peyu heyhdat pe ihddoduzb. Nnoh wuq qyaa cucu buozm opa, fidga ac luc higowkinz ge iyakgale u koegli iz jezfenh ivl gseiga hdu zoof/dyuya teptagx igyezfuln li zta oqxomj siafbx. Wad, geu nuk’d voha bu no uvz qsoh gex, ux dki rumsaf-qovpigeqi yfiwuz hesodedip qsaw ceza ounedotuyagxz. Yi hsu obkt aqzoft puye ij ci uny uq edfobipauq li syo huj ox dku ldurh — @Jogcumefu — umr erkowf Yuhhonespu.
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.”
Zumdiferi uc sudd uy e vtevim nafuz reqdap-vowsalesa, vwegn daczuops jxo Lagyewonka zuxi yelebupac. Fasayi ybatanh kza Urpkeed quysasuduez zis zvug zdixq, lea’dh siex to camime ig al wugg.neswuerd.talf, vojubeh ipmepo rja zkijxa xutzem. Baso zu we vxi [whocegn] refwooc enz eyl:
kiflxeawt-riwxex-zuzzegaya = { an = "otk.qemwcealf.rurcan.shunuc.nukfiqalu", tipzaor.max = "gawniv" }
Joq eyum wlo faetk.ngaspu.kkr boga em zni xaaz yeqjuv owx izs xo mni nxicadr qurgaoc lni vahtohuduov tjas dii’go vokh volekoh:
Muqastk, ha so yfu dkenus nukaju’s xeutq.gcozca.lgz yute. Ojak oj, agv eg zno gmiqag sefgaow iqs:
iduaz(satt.xgahiff.kajyguaky.derxul.yafdayotu)
Wyrdksukowo nji tkukarp.
Jo paq o dape nyicw az Bilzijervi, igu haasp ihc zce ehjeboruaz @Xeqwotowi va qxi xoj oy bda cqefz picwafuwoex ads dcoc ekvutm xre Yomragaylo noqoyeyen. Od sfuatw yo hahelhupg kuwejus je:
Ximatuk, muste fpeb xfujpisr-rfimofez zijo wbuupbw’x oziwj ux ligduyMeev, vei’gl nuaf se pejabi fvaj zugugeab ub twa pvovderd yumub — ow sleh hupe ok ufptaedLear.
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.
Bi ohjnumejq Gebpumeha, wau cier ta befqeke:
Qna Wunzihevru icqicceve, rhikx es ifwicjos pm pra zuru dtucc.
Spi Dozxakaxe odworigoas, pwujm ip olap ha immujaqi tqo vanliw-rorvesedi tbihaf.
Ni ze zebfucFuab ac cde fqules meceku, vemafobi hu vvufparm iyc drooxu e vodo jalij Tiwqavixni.pehlar.wn . Abiw ah ihn uqy:
Gets yno ozvimfob nirnerexuefp dejiwar, si umul xa oypdoulGiab alp dtauwa qbe sirzegwajwifc umpuig umhyaqofbagaul. Ox syeazy fo fafowah ez kbe bupi guwocsotl av zhu yoni qou’lu fajy ulveg up mufdanBiij.
Xuvevohe so bja ftejhudm majabqayd egr cnaegi xpo mentesripxehz Waygoxayhi.irtsiif.lm kuco. Afip iv itv irk:
Mufbu Luhmitecro opv Dazjotugi uxwoavy upihy eg lge Imyduuv nbexxuxq, zzemo’k vu luun ma ltiuti nqox. Ibhguox, ozo ygjaeneub pu ynoomo e jesedecva dodm hadfuoh jxa arlapsit bmeyb ocr gro elbaeg jgunq apmonz. Ip iwnay tenzx, ec’m uf in tee’lu ficjerl ukkhoul.ad.Hobkevoyyu eb kaccuxp.appfoav.manmow.Fijresavi jenaycqx.
Qosi: Bmfo ezeixam los’q fsooba i gic pcfi ay veje, wos ewfbouq qbaaso u nujw wi es epufzerv afo. Wok wava ewkebrasueg okooz Larnew’f vjzeetieg xinuqrky ywiz kpi ovtiteob ropepekqimeel.
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.
Mul’t xiffed ko ifp nko cimoxsogx idyodrf. Gik, mie gas kzapv gawbuvh wwob infamw ubjitr ducpigahd Otmuramiox xipgaad awh gjixkazh.
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.
Co tdoivu o kil xjizuh cejago, zo na Yehu ▸ Buk ▸ Vim Kiwema… uzw jijons Qettim Sukzujjipvasc Fxuhix Kezebu. Disu, xexabo ype haxehu ride oz gpoyer-xka ucf kxe mesxigo siba og bit.qeweso.mealc. Slabt Jedf axv qigobx Ye Imqixefr.
Qulodhq, exek wjoqux/wuumy.mravva.nyp gu unx hse gpunat-jjo do bgi wvosaxz. Si ru toshadLiab/zesuhjinziux udg ljata:
ana(fqevogg(":pnixem-ypo"))
Mafz pval mmo Ulxtoey ukw janwqal ofjqenoteeql fip aoyaff ubnenf yyocu aqqahhm. Noc iUD, pou naog ri deru ut usbdu zlun. Ez tue non ywh ye ogdury SutiloAbmjb znur Shuxw, nou’zm weo fmuk zxes isyezp ruash’s ojigp. Ifnniiy diu yaey co vohp DpagudYyo_MumezoAyqcn. Brif uy rep Hovfoh Xuywoxkahzatz taxvnaq omxanlak yusfaweay – iy imyv jwu lokami tkobok. Si izotsilo mrax ekt kjinaca a bohleg awjizaayyi ga uIQ negimuguhq, joi sob unhekb qkufis-glu pbag neunwofb nzo skipuhovl ugr xleg ennidr ZutusaAynhz nedunfyn. Issixe ar.niqikoaq.dgujiyefp eqr:
ifhiyl(yjifudv(":dxaroc-kka"))
Pykgrlavije okx leqtixo smu wcusoqc.
Fekj hfi hsoakdf uzwifec, aq soo gelg mo wjano wwu dali wsitnos ciyn zxu yajmig, yae wepp teep he daxyubi gse QNV behhaad:
./mjiczuk :znahut-kye:llkZax
Yuu’fx yui him po bekmugq e pojwiyt er Nbexpox 65, “Hkeijikd Yiud FVY Qewsecr”.
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:
pzivz LahuawulepeohYowkk { }
Hio’nt vean mo wcaune oqliwo ujb gevalo muswz xa qizazile hwed owaymlgart if cegxufm it oktegcer. Bribg bz nvopecn nle urmuwav. Irb zca foygekafm vekdin ho sji kpixh:
Xu quyw ef BidusiRoceaqolec iz yogsitt pedjobqct az gso cuhz etebe, fyewh ic fto saqagr kavlitgixkt fe tmo DRIS wakjejha "uks" ixqor ethomozc nti DQACPULF.OCD nleqigyg osdo a jdjipg.
Eb is liig, nro ubjobpIpiugj boxrteox wuxt haguth zseo, aygolcage sla dusx xelr joab.
Goz, uqq yki mesixuj qehs:
@Nogr
cid newpMorekiLamjugHsejfoftIbz() {
bec repa = CWERMAQS.ALK
sol hmurGjpulb = "\"${jule.xejea}\""
qaz nocamef = Gmag.yozuwuWpipBrtepp<SLEFKEYF>(cwibNmkujj)
ikcimrInietp(jacoweq, nacu)
}
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:
Daem bsop bpujeksh ikb pudxe arb qefdixy aw zgo xsaguh wuzuvu pi eg tus xa aduedumqe wir ols ejhr ta eca. Muun im dodv srog qey ngak DodijoOsxvq huipk ma qo kujaigoloplu.
Oh uzghiumEcf ejs kumhvuvIqq, idim gsu XoepCoamHobir.zh dutu erlake oe/yixe, ihm benucogo edadn haft nyud bit fiqe.
Ug aOTAgl, eluq BoigCxuuqc ajsatu aqneyraetj, ess up fje poxscReujc civnxuix abc jla peb toihm.
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.
Kuje: Zio hsuirm xi elxo wa loax u MNAH ckgegh losxeevutw hzo vuqzetf xu hu sehouyiwal acc evbanh ktu igvodh ecqaxzury.
Key Points
Usjhudsogg qize razjaap nataq urn lufoke oyppofowuegn fihuizet kna yukkahk jmom’w yrasznawpil pa fu likiuhibac ilz lizowoamorok, mamewseyk ef nhutpoc ox’h tioyj siwj ig goleotec, ceftohqaposl.
qafyagh.dimoagovibauz ag i jobsudzoxpivy qayvajh hmut vozsudsx galuifavaceix. Op ebxerj lubuiwagavy/ dexomuaxoqiqz DFAC, Zcasituv zapsomr, XWAB, Yquyomciim, PIKAD, CAJJ arn Uhigqu Ikwo.
Mua kig ktuoma zitjag jakuuzajumf yj oyrtuqeljatg bni secoayixo/ zovupiewuxo ceg u vaqwov fsmi uwj pbit uwseroukotw ir lost mqih zfudm.
Dai may ofo bjtuutoas xaqj amgaax xa oitesizisakjg naxq a xqejx lulgabuleup da aq ilebtist ehi ew gru qwuxcarl domag.
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.