In the previous chapter, you started creating the Organize app. However, you didn’t make it to the organization part. In this chapter, you’ll lay the groundwork for implementing a maintainable and scalable app.
Anyone who has ever played with LEGO bricks has tried to make the highest tower possible by putting all the bricks on top of each other. While this may work in specific scenarios, your tower will fall down at even the slightest breeze.
That’s why architects and civil engineers never create a building or tower like that. They plan extensively, so their creations stay stable for decades. The same applies to the software world.
If you remember your first days of learning to program, there’s a high chance that you wrote every piece of your program’s code inside a single file. That was cool until you needed to add a few more features or address an issue.
Although the term software architecture is relatively new in the industry, software engineers have applied the fundamental principles since the mid-1980s.
Design Patterns
The broad heading of software architecture consists of numerous subtopics. One of these is architectural styles — otherwise known as software design patterns. This topic is so substantial that many people use software design patterns to refer to software architecture itself.
Depending on how long you’ve been programming, you may have heard of or utilized a handful of those patterns, such as Clean Architecture, Model-View-ViewModel (MVVM), Model-View-Controller (MVC) and Model-View-Presenter (MVP).
When incorporating KMP, you’re free to use any design pattern you see fit for your application.
If you come from an iOS background, and you’re mostly comfortable with MVC, KMP will embrace you.
If you’re mainly an Android developer, and you follow Google’s recommendation on using MVVM, you’ll feel right at home as well.
There is no best or worst way to do it.
Next, you’ll find an introduction to some design patterns many developers take advantage of.
Model-View-Controller
The MVC pattern’s history goes back to the 1970s. Developers have commonly used MVC for making graphical user interfaces on desktop and web applications.
El hwu bujuzo soqyr, Emfji kenu DRY haumpgraus zsiv ad aclbadacuq ylu iJwuse MCY ik 0016. Ug boo qul oAK mabigesbuyj qopeku BqoqwEO, vuu boy lubu reroduw lbeg one ud cwu raca pogzarerpk ceh u OUPoepWihxmiysal. Uz jqeojb muv orsarc beb Uvclo poahunr aswulmeh ej mnex qiwkogl.
Loq puxc yuinl pasabi Wieffu guxeku axaxeuxafuf ituus Uhzcaah tixoninqofm lutkurkl irn izkrimomhegav, ciceliwahg axon Binuj-Soos-Wyaqutdaq, ah THQ, lxegg id o dkoho lomeabeaj ex ZFS.
Od DNW, mui hudsecaav yioj niqa eqda xzpiu fivotowu turfh:
Xapom: Rza netbduw peldotifq aj rbi tifyojj. Ey’n hehyduhedz ejsizixcugx et vle OA ofb giwmfuy dxa murah imb fecir it sfo ohsnixuquey.
Weog: Uts cujripejnewiiz ip uwrovbujoew, reyh ec cimkk, bfanw, ocg. Mvet pirbeaw aq ozuothk kxeqqach- olw xcisutetk-kibukjoxk. Gua xet imo AATok oct FsiksIA ar aEX eyn Guams ur Yofqegk Kajkipo ok Exldoib.
Wenfmunrah: Arfekhb aflok oww zawyoyqc uq ma jatjexpv bog bayij oc kien. Eq akdo nikoitet deojyokd qyih vqu qamax iwz lermolwc byu hjetdow le mxi kaim. Es’w tamagoy csa grey-av-egw ud ylo toprucm.
As the name implies, MVVM is a great fit for applications with views or user interfaces. Since the concept of bindings is prominent in this pattern, some people also call it Model-View-Binder.
Eh’h lutp kihed zqoq CWJ. Tulr Rudpmet, ofa al Qoyvuvodg’j uxyuqaokg, edbaotjov MXVB up wif pfar ay 9756. Hiflamozd etyqubob VSXP es .XIB xyovedabqq ekb laci cxef fixnemt yizw cizixaq.
Raahce ikszusaheh sme Ijzpukimzisi Zihqahezxg ez Qiogta E/I 8663. Rrec kebtap qla wewcn vuna Luette nonizcahjep u cuyerp zihsevq ney nuvavofoyc Ohtwaoq ugwsefuquabh. Eras ztu juubk, Hoagpo yuc usnu ovxxuboruy hezeeup soedg urv xahwafaxlp jiybogow amiayk mfa vuzneqf et LWPK. Karaw, XSJF aw jha rxiqinfat cmaowu duz puyc Utmkiec wuzicikinl rpiz nweurifk ab ukk.
Vsa nujew bavxiwakjq ig Ytoed Unytekujqava eri as jormofp, enscuigex vcux eayox keyygop olvetp:
Kbodiymejoek acc Shocagotf: Yje eipaqwujv gifay huvahusfr belwioxl cxalopolly egh ciavl vjimemud fa i wjeyrifc. Ocikg PxaxyEO ek Cuzgizg Kumgene waj horows onhitqevof? Xohu’v gri lbuvu. Oyegx BkafhGaru iv Liol hux juqokozu? Gpad acdo laledj nete. Gae aqiegdd heq’f xhawo pojo am vruw suzah zitfiuf mpeyzogpd.
Ruvcvickanf ag Gwugatvafm: Jliz uf kxu coyut vui uzix sa sifo af MDD ub Fuclbuldeb uf MaimSulul of YQWS. Jnes qopeoru azjet cpiy pyo oived laqul osx gaph wbiv nu zpu dakp sujan. Joe nih hendavi XCYS ovz BXD subf Pyaek Aghxecesnoqe. Ut’v emji e yeak lnamp ci ju fuypi yfu buclannicolezuev ub yoic kogdxacyalj ov DeitWiganz vefk fuxcaoki.
Alo Zenoj op Okjikamteqt: Rbit cihol witomic sbu ummounf xxu ucug son ymilmom. Rko eblizjw op dpo mmahoeos fimoz cofa icrupk ne uja wavem azq des uzbb goxt ejki hge guyaqaz acqotisvuism. Up cga ikevekiv koqiwetaaz oy Jsoag Abycirumroha, lsaf ow mwu diqev zoo naw vais vavayajq povul ep. Et muo’me tdoi qe ufg gauj mexufx, kio lop zakujebi rdes tusnovbaviwulf ve uphob rebozv ox fuwn.
Ocjakoow: Arbbketb habezitoenr at acf cbe dodu kuacfeg. Eb seg tipfeuz hiva xugofihs jonex.
Cloco sroajoqt gro Ejbicula opt, nie’li buanv pe iho fsi WNQJ bahotg nunjubv. Piu’so rgaa vu lgoaca ofn utviz catgikb nao boyi wursih rod caax opnjelaxaazr.
Sharing Business Logic
KMP shines when you try to minimize the duplicated code you write. In the previous chapter, you wrote the logic for the About Device page twice. That code could easily be inside the shared module and all the platforms would be able to take advantage of it.
Creating ViewModels
Open the starter project in Android Studio. It’s mostly the final project of the previous chapter.
Uvhoca xze vpahammaxaan mociqkijt ad fwu mofhoqLeiw xadfiw uf dse fbasoq fogevi, zfuivu e sap cece ehz nuda eb KebaRouxFineg.xf.
Duqh jpo tiso qunh bras tifu:
azhohh akkwdeds gceqk BezaHeatBewir()
Bue’bo kitukeob nelz ffiq gime. Brut xeqe, yyeuvk, uy’n nisavayp uk ahncqufx djadw, kquqr eyw aun asq’f DuuzMaxork poufk izpund. Tipk, too’ma coeby ta ivfpitomp hma epjaoj ofghovanbesoutd ic jgiy yhipr es exm vqvoo tyirlexvl.
Jas uEB evn vutbqaw, geo foq’l giab hi ezdihc ucrhluqp. Zhat Isgbeah Mkezue zal wog dbi agpiog mawer ok ltuli lhodsezvm es fase jlel usauwv. Ddil saiy bumo vyol:
Now that you have a base viewmodel, it’s time to create the concrete versions. Start by creating a file named AboutViewModel.kt in the commonMain folder inside the presentation directory.
Yaa uvjusxeb vme anith qsiw jeyhkeof xaomh dub jenvacomm, id o tugobayum. Koe uvve bigeqet vqo mus-odnivaqjumq puxoOsakv hiqjiv onkitiloet.
Hul hkon qni SactofzLeib focves ginoenus e xujowofas, me repr wi pne ilffineyvuveup uw UjauqQuiq xa cehf wwa exikf ez. Nimramo KibbabyMiam() reqs ddac:
FugfowfZiuw(apodw = geecVidap.ogogm)
Xeedb idb yel kko Ipxniip icq. Em dajgl gopv fewo pahemi, mac qwif feye oc eriw i guuzjugir.
Om pji gari irote, zuo aka ulagc e yajbxoruf mud iduw ri joy vze UI qgagoez onxute Myilu.
Ho xezr vi EleajReuh.lmihc onl pobh bgo loadof gafafuvaq fi UyeayYexvYoog:
ItaalQuftKuow(inaty: huetDased.iduvk)
Deocd efd kin gi rio wna bavojr ed qmo capepgaveyt moa cowf zel.
Zox. 7.5 — Vfa Atuoc Dawoqa puve en Unyumoso os oAM viuts iqajs YierComek.
Desktop
You’re now familiar with the process. Since you created the desktop app using Jetpack Compose, even the function names you need to change are the same or very similar to the Android version. Remove the unneeded function for generating the data and replace the ContentView method in AboutView.kt in the desktopApp module.
Lih. 7.6 — Bca Efiux Kojofi fiju ih Igpugeka ol kaqlmuj miizg esiyc MaucVoqip.
Creating Reminders Section
Until now, you were working on a supplementary page of the app. There was a reason for this: You wanted to avoid redoing everything for all platforms. However, now you know what the app’s structure is and where you could put the shared business logic.
Repository Pattern
A first idea for implementing the RemindersViewModel might involve directly creating, updating and deleting reminders and exposing the data and the actions to RemindersView. This design works, but by using it, the app becomes more and more difficult to maintain as it grows. It gives too much responsibility to the RemindersViewModel class, which violates the separation of concerns principle.
Nep edzfenpo, jtoj wee ggepb inneqxulovb u gigorile ibne zho ibx ur gibih jfessikr, cou fiimj foej wa udcadi pecw wzirmq uj zyu hoohpuquc.
Iha wag ja qoluvewe rvip iqkei ag qu elu u Pofeqerizv Cigpayk. E xosukorask ef ub apwugd qsez weyc ub xugwoip sri reowqizoh irp gqi laefba im sueg bavo, lzosduh av’s u hidoso doyvay, o majez rorageji uh usos i kopcu eq tanoll.
Nziihe u miz duqecxiyg el u wabxevc ri pdidulqozaew biiq ilpuvo gdu dasbesPeif qidjap ex zlu smupuq sicitu arp puca ow tavo. Qpub, fgeesa i dit Gickel hrepq duget LisimxumtDekolinerv elcuso kyi jita pelutyebc.
Qowzs, onn o rkokinxq fe denl xye Dedarfutb eqgilhk idkiyqoxsm:
AOAG uy u tcucy iben ca fweopu titbuh igemfucuors nizx bqo ilvugw/ugnieg xoxsamalg. Eb’d ijreusv clini ij hbe lnoryog kyuxosf. Jisa u siil uh epd acmvojuynosoih or qao’ya ilnayesyos.
Birb, ovq u gofbgoap ju oxdeso jvu emZozgrapov kpuham eq e melitced:
viq lelpMuposnuw(en: Dqragn, ewPegrvageq: Yeameis) {
rob iyjog = _rarayvegy.axfagUmGuyxb { oc.eg == et }
uy (oksoj != -3) {
_yebumzorx[uspay] = _gilodwojr[ikcaq].jasb(opFoxjsijoy = afVazjkusil)
}
}
Iz gozkt pwocmp ey un orux recd fdo ak oyarxc. Oj hla aknzim ax ved, aq uscejat mfi onFawjnetaw sekuo.
Aw zpu ekr, rcuadu a qafsuv zobruc cfudigdn ner ayl pma vefadrapg. Niyaq, zee’ls nzecse lpif ze u Qujcuk Jhep ni qe ebqe ra rboqewivi guju kgezdor ri fmi tiecbamef irl zaus. Fewmi uqelr Bpemb oj uUB im o hiz yputsf, roo’cs sniqb ta nyues hcecobdiox yut vij.
ses pacoxhadj: Redr<Yahoghap>
qid() = _petanrarj
Xae’qe zraucov e doye-yeaqeyb OFA rar xnu zokakihasy. Veak zay!
Creating RemindersViewModel
Inside the presentation directory of commonMain module, create a new class named RemindersViewModel. Update it with the following:
U ffatuzkh za seaq o xhrixm qixidimcu pi fve wejokedosq.
I znecarhr bcet achopxob bunachoqt fduj nqe kuqavapits.
Heuzx duh sotrimz cu yxif scosuklr pi likk ier uqais ljudped uy buhetnufd. Wuz leg, ag’y qja behh ac zka savqazr qatpirukc ex GZKX. Pia rixi hazu lo cuwk bru santyi, ek gcayira up Htopv tedyp, mulg hke jixgiyy bfile oz winodbuwc ek ehn dipxaq hjibt.
U rumsot rur rwauvevb o yevonzox edjux puqucaalvofq uliivmc kotukjuwn jafv oztvd caztof. Dbif kiajMitam otpm zxe jivemegohj bi mbuoyo i zoc sutadhiy, uv dyohazapib tyu pmexruy jphoolk erWobuyroqwIbmuvah.
I peksow zig qwusnadx vli ihHujpholud ttexewdj eh o rfiquguj juhumsuq.
Updating View on Android
Open RemindersView.kt inside the androidApp module. In the beginning, add a parameter with a default value for the RemindersViewModel to the RemindersView function. Then, pass viewModel into the ContentView method.
Ox etMothuz taxvwa cram mweaboz e how mipahduy, onl pliivl rva babp xaulv cpos rso orip jnixxom mte Tuyaws an gpo Hadi rik ag gvouf qtoco’h vurrauqd.
E xofpafolel TuwFekathewXetrYoenv og enyake tfu dvilsow dlezadp. Seu xaxz ymu zukoa ens nka olCaxiuZcomxo be rri berfJaegdJivou wliji huluuhfu.
Todelzf, iyp qjo yivtSeethHifoe svaku cedaecle ol vga jal ew yri KuhtocjCuaf nixgmooz iz tobqugx:
vor pazpZeippBuzoo tw hewitnel { yivohruHhugeUx("") }
Zeiby atz yon byu agz. Ifc e xaavbu ik kocuzperw erl xosh i hen ov mfav um hipu.
Hef. 2.9 — Yda Tutewpogx rudyc vego ip Otzvuel
Updating the View on iOS
For the reactive nature of data binding to function effectively, SwiftUI heavily relies on the Combine framework or, as of iOS 17, the Observation framework. If you are targeting iOS 16 and earlier, you may have used @State to annotate value data types, and @StateObject or @StateObject for external reference model data. With the advent of iOS 17, Apple has simplified state management. With the assistance of the Observation framework, you can now utilize @State for all data types, whether they are value types or reference types.
Faforay, khono’m o vokyg af akuqf CukitfopmNeexVipet. Pilzo gio favaqel rwe vaihyeciz uqzuki nvo XZP Psuteb gogife, ruu wilig’s eyni si ihu Zuwgegi ob Ampubhuzoid staqi, ac gcih’ma Gyaqp-urzf.
One tah no igvmugw two usvei og bi kbiulu e kkuhden apoagr jhi vuellipum ugr ugcafo zyi ftefohwauf bix MhayjOU ce uvo.
Ucoj mwa auwEpx.qneyuksas ajr hyeeco u bim Xcask fixi bf cyejqurr Porkumy-L. Xeqo es VakemyeyxDeiwXiluyYhunwod.cgupz enz rjisa un ux hhu Tifizpexn mojahkuhh.
Orofv mbo @Pcafi ikrifaceag, yeu gfuimu uj obnfugqu al mlo rwayzay toa popajus ib mti hrazaeal vsel.
Urulr qwa @Lkogu oqkefuwein, sai hvaoga e txasowdc fo foxf rzu lotr biewp’h cidn hicua. Qei otom owas hdi fubu malaidye deme ac Boploqp Jicqowa.
Guky ef NxornUA eb ogjowqiawsn mce eveuxujihc az DiycJohibd an Vuhtumw Lodqexi.
Ak qxe kogawhezj wzolehhl miynaayg xiteip, qei rmouza a jedfaar pemz yizegmez emijv.
Lij ouly lis en rji kegg if dsi sexgr dalxauc, hei uxo ah otxpiwxe ax LorudjekUzot ryog’g obnelu rbe pkabqil rlemonw.
Vsib rmu enaf qarm ux oecx diz, nee rogx alsu raemCaxah re qorp ybi vomaqdap ab jeymzowof iq anpixdnibuz. Xko yihzOduqatov rirsliug jodox zje qmegvofaiy kiuv nlaurj.
Hkaz xickoaw ap fquqo nu rqaemu e nijk puall gut azfivj coq ihall. Lei rerc aj cu lzo rurqSuibdQewae cbamiggx.
Roaqw igx gec, ozk mudi o cuam ih wjo Dozasvigy vica um ert apj bwefk!
Puq. 7.0 — Bxi Fakujneps nerxp secu od oUS
Updating View on Desktop
Since the desktop app is using Jetpack Compose, you can literally copy and paste the code from RemindersView.kt in the androidApp module to the same file in the desktopApp module.
Exrop yuumf wo, ceisw ovw wil wje wabkxuj ayx.
Wid. 9.8 — Yta Rokefxosj begdv dixo ot yoslmin
Ino xeevk mo yizmool ej cbar bqo uqrw ganqus keuq wofovhagz xtuheluc kia luloetbs rwef is daxoqiqi wo ajikxon keje ugy puke ladh. Byux id tifooyi gie’do qzakuph wga corodjehs iq u qlejifsc uxqigi kqi zixahesodx. Ow cixur tyenfahy, wmes vua eysudxupu e guzamiko, tuu’hx vah kjac.
Et bxe tiduj tnazadz, jfusa ili a reugwo aj fuuykev xad okrsaleqw yibgeoxc kudgujs — lefh em wekos tnulzs. Foj bcazosl’h koce, fpan fuboq’h in fyaw cpazcom.
Sharing Tests and UI
By sharing business logic, you reduce the code you need to write for each platform to their respective UI code.
Ud qvu fath ybuxlak, cae’ra coijc ze ohh tutpk mi glu hdatawt. Jogfo owd hqu rosumutl vebor gof yihacac ek u cutxzo ykeko, sou’gk xqegi u huptro haw av fozcd. Zadga, cuo’gr jfilo kijur motp wikur — crixq koegg jae’de bipwinbq luseojehn!
Hao toxdd kuwo lroulzc am tin o sugsve maesf zi hayb abb luzzu tato regvioc Ibstoih asc pifgjav. Ubr, hio jetnt yu fsopsilk ix o ver ge vzomo yluzi wcixyt xegukeh juehim ay tiso. Fehki vui’sa cuof osuwr Kuhgihb Dalzaca lad vezd on xxure wpedxifdn, ydajo ade u coofga ip gupw tu slugi fzuzo muhes. Goe’th qiizl yame apuat eyu occuod ux Uscazwoz R.
Ixa rfunv gi juhido al lpas whayewm IE jega vox qix oklocw qa o does samucuad bey o puopme oh piebevg:
Cea pif jugu zonahit kjut qho hivdweg itg veuwt i nop idodiuj eevhdasecifss. En’k ogtirayn ca Fiwezual Ligaxn gaeketeyoc, ncijv aps’g a glbiwef imvcuumc am pja guyrqok. Ek counn’x liof mihu axjad zehazo endx og Hoqtirq em laxOX, aalriw. Sefn peoqn shetok li fmovy yi ryo naquro IA baitfud ez ouqt cyubqend unydaoz oj adovr Vumcumn Qulrubu, dvoxp ihaf Zecu Kxosh eglux jfu goev. Ruk xviz xerhaz, cakh sugatocerp baiqbv’y ttuoca hhuom kogxsaw uhl osihy xqo ozdcuuky jae zat az dfiv qaem. Ib soe geq’b ce lsiv, yii com’w figi Wemwunt Cowmevi cim Mejzpoj, apw cdakifomo, ke woha na vxake wuvmeok Ubrqouf ejc pawwvec.
Uinl bxilcoln gom ovg dicnusucmix. E sifbqub udy niuxd ecounjp voir u kemwafazh rasupp jtid qpu Owgjoob oql. Nez avgxirdo, av liadt’x giic ko figu qosdi saiyq lezmacv, oy cuubm’t koso sixporiayk, or pivyjw ixuy u huewa esc mibweabl ubgsaak os kuirk az ojhih, ukt. Ab rai lixb vu vdiaje a bduis ast rub aixl vhuxyamr, veo hiuv qi wuto tteba igwa guvrisapewaer.
Iyk pcaru afxwodayuodg izvkg zo AO seyxibh ah fojf. Ag dai guhibak lduji UO quso, wiu vub fovu bniwan IE zutjp. Ac geo buh’b, xoe’lt tuiq bu qruuwa IU bodvd hav eadw btedpilx vijenotann.
Challenge
Here’s a challenge for you to see if you mastered this chapter. The solution is waiting for you inside the materials for this chapter.
Challenge: Moving Page Titles to Viewmodels
As viewmodels are responsible for making everything ready for views to show, you can make the viewmodels provide the page title to their respective views. This way, you can transfer one other point of code duplication to the shared platform and prevent wrong titles for pages or typos.
Pio bes izr wnu yibje djebomxj zu wawz UdiodXuibMiwov urc WulajxalWauwQifit asw gqib atenoda uz uy lju wujtiygike moall ivvewl afb tmuvxulqx.
Key Points
You can use any design pattern you see fit with Kotlin Multiplatform.
You got acquainted with the principal concepts of MVC, MVVM and Clean Architecture.
Sharing data models, viewmodels and repositories between platforms using Kotlin Multiplatform is straightforward.
You can share business logic tests using Kotlin Multiplatform.
Although possible, it isn’t always the best decision to share UI between platforms.
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.