<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Getir - Medium]]></title>
        <description><![CDATA[As the pioneers of super-fast delivery, we’d like to share our thoughts regarding what to do and the values we have as a growing people organization. - Medium]]></description>
        <link>https://medium.com/getir?source=rss----5138a1e0a250---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Getir - Medium</title>
            <link>https://medium.com/getir?source=rss----5138a1e0a250---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:14:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/getir" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Part 11 How We Migrated a Live Courier App Without Pausing the Product]]></title>
            <link>https://medium.com/getir/part-11-how-we-migrated-a-live-courier-app-without-pausing-the-product-d134362f9544?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/d134362f9544</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Bulut Serel]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:15:18 GMT</pubDate>
            <atom:updated>2026-11-16T08:15:17.613Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac?source=post_page---user_mention--d100fd0bdac2-----------------------------------------">Erdem Uysal</a>, <a href="https://bbasoglu.medium.com">Bünyamin Başoğlu</a>, <a href="https://medium.com/@enesarisoy">Enes Arisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHqESZ26px0H5du-VsXIKw.png" /></figure><p>Most apps can afford a pause. You freeze a few features, rebuild something behind the scenes, and bring people back when it feels ready.</p><p>A courier app does not work that way.</p><p>While someone is on a shift, the product is part of the operation. Tasks keep moving. Location keeps updating. Realtime updates keep arriving. Maps, scanning, and camera flows are not nice-to-haves — they are how the job gets done. If the app becomes unreliable, the field feels it the same day.</p><p>So when we started moving our courier product toward a shared Android and iOS architecture, the hard question was not “what stack looks clean on a slide.” It was simpler than that:</p><p><strong>How do you change the foundations of a live product without stopping the product?</strong></p><p>This is the product side of that story.</p><h3>What MDU actually is</h3><p>MDU sits in the middle of Getir’s courier operation.</p><p>On the surface, it looks like screens: login, home, go to task, delivery, subtasks, and a handful of supporting flows. Underneath those screens, a lot more is going on. Active task state. GPS. Geofencing. Realtime connectivity. Telemetry. Background coordination. Maps. Barcode and camera workflows.</p><p>That mix is why MDU never felt like a normal consumer app to us.</p><p>In many products, closing the app is fine. For us, the product still has responsibilities while the courier is working. A push notification is not just a message — it can sit next to task state and realtime behavior. Location is not only a pin on a map — it feeds geofencing, recovery paths, and operational signals.</p><p>If you treat that as “just UI,” you miss the product.</p><h3>The product problem we were trying to solve</h3><p>For a long time, Android carried most of the operation. As we expanded toward iOS, building a second, fully separate version of the same product behavior did not feel like a good long-term plan.</p><p>Two teams. Two interpretations of the same flows. Two places where bugs can diverge. Two places where a product decision has to be re-explained.</p><p>We also could not freeze the roadmap and rewrite everything from scratch. Features still had deadlines. Bugs still needed fixing. Incidents still happened. QA still needed stable builds. Couriers still needed a working app every morning.</p><p>So the goal became fairly clear:</p><p><strong>One product core. Two platform hosts. No pause in the field.</strong></p><h3>What we chose to share — and what we did not</h3><p>We were not trying to pretend Android and iOS are the same operating system. They are not. Background behavior differs. Permissions differ. Lifecycle differs. Native device integrations differ.</p><p>What we wanted to share was the part that should mean the same thing on both platforms: product behavior.</p><p>That includes things like:</p><ul><li>how a flow should behave</li><li>what state a courier should see</li><li>how networking and persisted state are handled</li><li>how screens express intent</li><li>how navigation should move between destinations</li></ul><p>The platform-specific mechanics — maps, camera pipelines, sensors, location providers, permission dialogs, background hosting, push entry points — stayed at the edges, where they belong.</p><p>In plain words: <strong>share the product decisions. Keep the operating system honest.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWokp237n_3kJn_RQa2eAQ.jpeg" /></figure><h3>Why the order of the work mattered</h3><p>It is tempting to start a multiplatform story with screens. Screens are visible. Screens feel like progress.</p><p>We deliberately did not start there.</p><p>If you change networking, storage, presentation, navigation, and a second operating system all at once, every failure looks the same from the outside: “something broke.” You do not know which layer caused it. That is a bad place to be when real couriers are using the app.</p><p>So we moved one major boundary at a time.</p><p>First we put the new shared foundation into the existing Android production app and let real traffic exercise it. For us, that proving period was roughly two months. Only after that foundation had lived under real usage did we put more of the shared presentation and navigation on top of it. Then we expanded carefully.</p><p>The sequence mattered more than any single library choice.</p><p>And “ready” did not mean “it compiles” or “it looked fine in a demo.” For this kind of product, maturity comes from real operational exposure.</p><h3>What continuity looked like day to day</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgYZ7kdiJtRH8fKL85AfmQ.jpeg" /></figure><p>During the migration, normal product work did not stop.</p><p>New features still shipped. Bugs still got fixed. Other teams still depended on Courier Mobile. Old and new paths had to live side by side for a while.</p><p>That overlap was intentional.</p><p>Where we could, new work went into the new architecture. Existing flows moved gradually. Legacy paths stayed alive until their replacements had enough production history. Temporary dual maintenance was acceptable. Permanent duplicate product graphs were not.</p><p>We also tried to keep unfinished crossings visible. If nobody can name what is still temporary, temporary architecture has a way of becoming permanent architecture.</p><p>From a product seat, that discipline mattered as much as the technology. Continuity is a product requirement, not an engineering afterthought.</p><h3>What we got out of it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mdnxycdGrX1umseIN4BTw.png" /></figure><p>What came out of this was not an Android app copied onto iOS, and it was not a clean-room rewrite either.</p><p>It was one production product, moved step by step onto a shared core.</p><p>That gave us a few things that matter in product terms:</p><ul><li>one place where courier behavior is defined</li><li>less chance of Android and iOS drifting into different products</li><li>a path to expand platforms without stopping field operations</li><li>a team that can ship features while the architecture underneath keeps changing</li></ul><p>Compose Multiplatform helped us share presentation. Kotlin Multiplatform helped us share much of the behavior underneath it. The useful metric was never “how many files are shared.” It was “how much product behavior has one implementation.”</p><h3>If you only take one thing away</h3><p>Migrating a mission-critical courier app is not mainly a UI project.</p><p>It is a continuity project.</p><p>You protect the product that couriers already depend on. You share the decisions that should be the same everywhere. You leave real platform differences at the edges. You prove each step under real usage before you put the next step on top.</p><p>That is how we changed the architecture without asking the operation to wait.</p><p><em>If you want the deeper technical path — infrastructure cutover, presenter contracts, navigation, permissions, session ownership, realtime, and the rest — that lives in our Compose Multiplatform migration series in Confluence (Parts 1–10).</em></p><p><em>From Getir Core Courier Mobile — notes from a production migration, written from the product side.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d134362f9544" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-11-how-we-migrated-a-live-courier-app-without-pausing-the-product-d134362f9544">Part 11 How We Migrated a Live Courier App Without Pausing the Product</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 10 — The Playbook: What We Would Repeat, What We Would Not]]></title>
            <link>https://medium.com/getir/part-10-the-playbook-what-we-would-repeat-what-we-would-not-6a68628cb06f?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a68628cb06f</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:15:03 GMT</pubDate>
            <atom:updated>2026-11-16T11:12:30.506Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGj8keCEYrPLWQEhcWCKmg.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 10 of 11</em></p><p>Parts 1 through <a href="https://medium.com/getir/part-9-platform-edges-facades-around-the-product-shell-ef8854c42992">part 9</a> covered the production migration itself. This part turns that experience into a practical migration playbook.</p><p>It is not a framework checklist, and it is not an argument that every Android app should move to Compose Multiplatform. It is the set of rules we would use again if we had to move another mission-critical Android product toward Kotlin Multiplatform and Compose Multiplatform while keeping production running.</p><p>The main constraint matters: the product cannot stop while the architecture changes underneath it. That constraint shaped almost every decision in this series.</p><h3>The Strategy in One View</h3><p>The strategy we ended up trusting was:</p><ul><li>share product policy in Kotlin</li><li>keep OS and vendor mechanics behind explicit platform boundaries</li><li>migrate incrementally rather than rewriting</li><li>validate shared infrastructure on Android production traffic first</li><li>expose CMP destinations only after they are mature enough</li><li>keep unfinished migration work visible</li><li>accept temporary coexistence</li><li>avoid permanent duplicate product graphs</li></ul><p>Compose Multiplatform helped us share presentation. Kotlin Multiplatform helped us share much more of the product behavior underneath it. expect/actual, facades, and thin platform hosts let Android and iOS stay different where they genuinely needed to be different. The sequence from Part 1 mattered more than any single library.</p><p>The critical validation step happened before iOS carried serious production responsibility. We ran the multiplatform infrastructure inside the existing Android application first, for roughly two months. That meant Ktor, Room Multiplatform, DataStore, serialization, DI coexistence, and shared business infrastructure could fail under an environment we already understood before a second operating system was added to the equation. We did not want to debug all of these at once:</p><pre>new HTTP stack + new storage stack + new serializer<br>+ new DI model + new UI framework + new operating system</pre><p>Each of those changes can be reasonable on its own. Introducing them together makes failures much harder to isolate. A migration should steadily reduce uncertainty.</p><h3>Definitions We Used During the Migration</h3><p>Some migration discussions get confusing because the same words mean different things to different teams. These are the definitions we used.</p><ul><li><strong>Share:</strong> move product meaning into commonMain so Android and iOS consume the same behavior.</li><li><strong>Fence:</strong> keep operating-system or vendor-specific mechanics behind expect/actual, facades, or thin platform hosts.</li><li><strong>Strangle:</strong> grow the new architecture alongside the legacy system and cut traffic or destinations over gradually.</li><li><strong>Canary:</strong> run a new shared layer under real production traffic before expanding how much of the product depends on it.</li><li><strong>Dual maintenance:</strong> temporarily maintain the legacy and shared paths while a crossing is incomplete.</li><li><strong>Session lifetime:</strong> the lifetime of the authenticated courier operation.</li><li><strong>Screen lifetime:</strong> the lifetime of a destination, ViewModel, or Compose presentation.</li><li><strong>Host:</strong> the Android or iOS shell that connects shared Kotlin to the operating system.</li><li><strong>Maturity:</strong> a feature or journey being reliable enough to expose more broadly under real courier usage.</li></ul><p>Maturity does not mean it compiles, and it does not mean it worked in a demo. For this kind of product, maturity comes from real operational exposure.</p><h3>Strangler Rules That Worked for Us</h3><p>Incremental migration only works when coexistence is deliberate. The rules we would keep are:</p><ul><li>keep legacy and shared paths explicit</li><li>preserve DataStore identity during migration</li><li>preserve storage keys and payload shape</li><li>treat @SerialName, enum values, nullability, and defaults as compatibility concerns</li><li>cut HTTP traffic over feature by feature</li><li>allow Hilt and Koin to coexist only with explicit ownership</li><li>never create duplicate owners for tokens, databases, sockets, or long-lived service state</li><li>do not wait for the whole application before shipping one migrated feature</li><li>when a legacy feature is changing heavily, prefer completing the crossing rather than expanding the old implementation</li><li>send new work into the new architecture where practical</li><li>mark unfinished migration work so it remains searchable</li><li>remove the legacy path only after its replacement has production history</li></ul><h3>What We Would Share Early</h3><p>The first candidates for shared code are the areas where Android and iOS should agree on the answer: domain use cases, repository contracts, shared data and serialization models, stable wire-format names, DataStore and Room access, networking policy, DTO mapping, ViewModel Action / State / Event contracts, the sealed Route graph, navigation policy, session-service ownership, handler coordination, permission sequencing, analytics event language, logging call sites, and push interpretation after platform delivery.</p><p>These layers benefit both platforms before the UI is completely shared. They also make later screen migration easier because the screen is consuming a core that has already been exercised in production. A useful heuristic is:</p><pre>If Android and iOS must agree on the product answer,<br>the decision probably belongs in shared Kotlin.</pre><h3>What We Would Keep as Platform Edges</h3><p>Some things should remain platform-specific. That is not a failure of KMP. They are genuinely tied to operating-system or vendor behavior: map SDKs, ML Kit and camera pipelines, sensors, location providers, native geofence APIs, Android foreground-service hosting, iOS background-execution mechanics, Manifest and Info.plist declarations, Activity Result APIs, iOS authorization APIs, APNs and Firebase integration, vendor analytics and Crashlytics SDKs, and OEM-specific Android behavior.</p><p>Shared code should see models such as:</p><pre>DetectedBarcode, Location, SensorEvent, PermissionResult, Route, AnalyticsEvent</pre><p>It should not need to import:</p><pre>GoogleMap, GMSMapView, CameraX types, AVFoundation types, android.hardware.Sensor,<br>CLLocationManager, FirebaseMessagingService, FIRCrashlytics, CLAuthorizationStatus</pre><p>The percentage of shared files is not the metric that mattered. The amount of shared product behavior is.</p><h3>Cutover: Android First, Maturity Next, iOS After</h3><p>The cutover model we would repeat is:</p><pre>migrate destination into CMP<br>      ↓<br>open on Android<br>      ↓<br>prove under real courier traffic<br>      ↓<br>open on iOS when mature enough<br>      ↓<br>continue moving remaining destinations</pre><p>Do not wait for the entire application to reach 100% CMP before exposing any shared features. But do not expose an incomplete journey simply because its screen exists. And avoid building temporary native iOS copies for features already moving toward CMP.</p><p>Android-first without a shared graph still leaves iOS as another rewrite. A shared graph without maturity gates creates pressure to expose too much too early. Both parts matter.</p><h3>Dual Maintenance Is Temporary Architecture</h3><p>We had dual maintenance in almost every layer. The right response was not to hide that complexity. It was to make it explicit:</p><pre>old + new coexist<br>      ↓<br>ownership stays explicit<br>      ↓<br>crossing is completed<br>      ↓<br>legacy path is removed</pre><p>Temporary dual maintenance can be the safest form of architecture during a strangler migration. Permanent duplicate product behavior is where it becomes dangerous. If a team cannot name what remains unfinished, that unfinished architecture tends to become permanent.</p><h3>Decision Matrix for New Features</h3><p>During migration, new product work still arrives. For each feature, we would answer a few questions before implementation.</p><ul><li><strong>Destination:</strong> can the feature land directly in CMP using the shared Route and ViewModel model?</li><li><strong>Platform edge:</strong> does it require a genuinely new native integration, or can it reuse an existing boundary?</li><li><strong>Lifetime:</strong> does the work belong to the screen or to the courier session?</li><li><strong>Permission:</strong> does the capability need startup permission or feature-scoped permission?</li><li><strong>Observability:</strong> can analytics and logging go through the existing shared boundaries?</li><li><strong>Crossing:</strong> are we expanding legacy code or completing an existing migration boundary?</li><li><strong>Visibility:</strong> is unfinished migration work clearly marked?</li><li><strong>Host impact:</strong> does Android need a new launcher, service type, or lifecycle integration? Does iOS need a new authorization flow, Info.plist entry, or Swift bridge?</li></ul><p>When those answers are clear, new features generally strengthen the architecture instead of creating another temporary island.</p><h3>Definition of Done by Layer</h3><ul><li>Infrastructure is not done when it compiles. It is done when state survives upgrades and real traffic.</li><li>A presenter is not done when a screen renders. It is done when Action, State, and Event responsibilities are clear and one-shot effects cannot accidentally replay as state.</li><li>A route is not done when a composable exists. It is done when arguments, deeplinks, and migration status are explicit.</li><li>A device integration is not done when the SDK initializes. It is done when Android and iOS expose the same product-level semantics.</li><li>A permission flow is not done when the dialog appears. It is done when declaration, sequencing, denial, Settings, and re-entry all behave coherently.</li><li>A session handler is not done when it works once. It is done when start, stop, ownership, cancellation, and logout behavior are predictable.</li><li>A facade is not done because one provider works. It is done when product code no longer needs to know which provider sits underneath it.</li></ul><h3>Failure Modes We Learned to Recognize Early</h3><p>Some patterns repeatedly indicated that an ownership boundary was wrong.</p><ul><li><strong>Screen-owned sockets</strong> work until navigation destroys the owner.</li><li><strong>Sticky navigation booleans</strong> work until recomposition or restoration replays the effect.</li><li><strong>Independent iOS routers</strong> work until route arguments, deeplinks, and product flow drift.</li><li><strong>Fake portable SDK abstractions</strong> look clean until real OS behavior no longer fits the abstraction.</li><li><strong>Incorrect permission ordering</strong> looks harmless until required background capability never reaches a valid state.</li><li><strong>Socket-as-background-location</strong> looks fine while the realtime channel is alive and silently fails when it is not.</li><li><strong>Immortal handler scopes</strong> simplify construction until logout leaves operational work running.</li><li><strong>Hidden migration debt</strong> makes the architecture look complete until nobody knows which implementation is authoritative.</li></ul><p>When one of these patterns starts appearing, the right time to fix the boundary is early. Not during the next rewrite.</p><h3>What We Would Repeat</h3><ul><li>using Android production as the infrastructure canary before depending on iOS</li><li>strangler-style coexistence</li><li>storage and serialization parity during cutover</li><li>one ViewModel contract across features</li><li>one sealed Route graph</li><li>expect/actual boundaries around native SDKs</li><li>ordered permission flows that respect platform asymmetry</li><li>one session service with one session-owned CoroutineScope</li><li>shared socket, geofence, telemetry, and backfill handlers</li><li>a thin Android foreground host and a genuinely different iOS background host</li><li>keeping realtime socket behavior separate from background location delivery</li><li>shared push, analytics, logging, and crash-reporting facades</li><li>feature-by-feature migration with visible markers for incomplete crossings</li><li>a thin Swift shell around a Kotlin product core</li><li>one team evolving the shared multiplatform product</li></ul><p>Most of these choices did not maximize how many files were technically shared. They maximized how much product behavior had one implementation. That was the more useful metric.</p><h3>What We Would Not Repeat</h3><p>We would avoid:</p><ul><li>combining UI, DI, networking, serialization, and iOS introduction into one big-bang migration</li><li>moving Android implementation details into commonMain simply to make iOS compile</li><li>allowing screens to own sockets, telemetry, geofencing, or session lifetime</li><li>using sticky booleans for one-shot effects</li><li>rebuilding navigation independently per platform</li><li>pretending iOS has Android foreground-service semantics</li><li>treating a connected socket as guaranteed background-location transport</li><li>leaking Manifest strings or iOS authorization enums into ViewModels</li><li>hiding incomplete migration behind “it works”</li><li>measuring progress only by the percentage of files moved</li><li>optimizing for diagram purity instead of production continuity</li></ul><p>The migration is complicated enough without hiding the boundaries that make the system understandable.</p><h3>Team and Product Reality</h3><p>This was not a laboratory rewrite. While the migration was happening, Android production remained active, product development continued, courier operations continued, iOS was introduced through a thin host, and the same Courier Mobile team carried most of the shared Kotlin core.</p><p>That constraint shaped the architecture. We optimized for continuity while the product was under load.</p><p>Multiplatform became valuable for us not because it made simple screens shareable. It became valuable because one team could carry one operational product core across Android and iOS without stopping the field operation to rebuild everything.</p><h3>The Final Playbook</h3><p>If we had to give another team only ten rules from this migration, they would be:</p><ol><li>Canary shared infrastructure under existing production traffic first.</li><li>Preserve storage and serialization identity during coexistence.</li><li>Standardize Action / State / Event before multiplying shared screens.</li><li>Own route identity in common code.</li><li>Share product policy and fence native SDK mechanics.</li><li>Order permissions deliberately and respect platform asymmetry.</li><li>Put operational work under one session-owned service scope.</li><li>Do not confuse realtime socket lifetime with background-location continuity.</li><li>Keep vendor SDKs behind explicit facades.</li><li>Open only what is mature, and keep unfinished migration visible.</li></ol><p>That is the playbook we would use again. Compose Multiplatform was not the whole solution. It was one layer of a shared product architecture that first had to prove itself under real courier traffic.</p><p>The goal was not to make Android and iOS technically identical. The goal was to give both platforms one business core while still allowing each operating system to behave like itself.</p><pre>One product core<br>Two platform hosts<br>Temporary bridges<br>Visible migration debt<br>Production-proven cutovers</pre><h3>Next</h3><p><a href="https://medium.com/getir/part-11-how-we-migrated-a-live-courier-app-without-pausing-the-product-d134362f9544">Part 11</a> tells the same migration from the product side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a68628cb06f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-10-the-playbook-what-we-would-repeat-what-we-would-not-6a68628cb06f">Part 10 — The Playbook: What We Would Repeat, What We Would Not</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 9 — Platform Edges: Facades Around the Product Shell]]></title>
            <link>https://medium.com/getir/part-9-platform-edges-facades-around-the-product-shell-ef8854c42992?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef8854c42992</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:14:49 GMT</pubDate>
            <atom:updated>2026-11-16T11:12:13.191Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEpaPEGeyMMFUkOhTrLB7g.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 9 of 11</em></p><p><a href="https://medium.com/getir/part-8-realtime-telemetry-session-behavior-not-screen-accidents-b9427aba1494">Part 8</a> covered the programs running inside the courier session: realtime communication, geofencing, telemetry, and GPS backfill. Those belong to the session service rather than to individual screens.</p><p>Part 9 moves one layer outward. Even after the operational session is shared, several platform-facing integrations still surround the product:</p><ul><li>FCM / push intake</li><li>analytics</li><li>logging</li><li>crash reporting</li><li>lifecycle integration</li></ul><p>The goal is not to force these SDKs into commonMain. The goal is to make them usable from shared Kotlin without letting vendor APIs spread through every feature.</p><h3>The Platform Edge Pattern</h3><p>The pattern is the same one we used for maps, permissions, sensors, and background execution:</p><pre>OS / vendor API<br>      ↓<br>thin platform adapter<br>      ↓<br>shared contract / use case<br>      ↓<br>product behavior</pre><p>Common code speaks in product concepts. The platform host translates operating-system behavior into those concepts. Vendor SDK types stay behind explicit boundaries. The implementation can differ a lot between Android and iOS. The product contract should not.</p><h3>Push: Two Platform Doors, One Product Path</h3><p>Push is not a second implementation of courier business logic. It is another transport into product behavior the application already understands. A push payload may represent:</p><ul><li>a new task</li><li>a client note</li><li>a restriction update</li><li>a popup</li><li>an unread notification</li></ul><p>What matters is what happens after the platform receives the payload. The shared path looks like:</p><pre>FcmPayload<br>      ↓<br>toFcmMessage()<br>      ↓<br>HandleFcmMessageUseCase<br>      ↓<br>existing domain behavior</pre><p>Token registration follows the same idea:</p><pre>platform messaging token<br>      ↓<br>shared Kotlin<br>      ↓<br>backend registration</pre><p>That keeps push handling from becoming a parallel business layer.</p><h3>Android: FirebaseMessagingService</h3><p>Android owns the operating-system entry point through FirebaseMessagingService. The two important callbacks are:</p><pre>onNewToken<br>onMessageReceived</pre><p>A simplified implementation looks like this:</p><pre>class FCMService : FirebaseMessagingService(), KoinComponent {<br>    override fun onNewToken(token: String) {<br>        super.onNewToken(token)<br>        scope.launch {<br>            setNotificationIdUseCase.once(token)<br>        }<br>    }<br>    override fun onMessageReceived(remoteMessage: RemoteMessage) {<br>        val content = remoteMessage.data[&quot;content&quot;] ?: return<br>        val payload = json.decodeFromString&lt;FcmPayload&gt;(content)<br>        val message = payload.toFcmMessage(<br>            json = json,<br>            title = remoteMessage.data[&quot;title&quot;],<br>            message = remoteMessage.data[&quot;message&quot;],<br>        )<br>        if (message != null) {<br>            scope.launch { handleFcmMessageUseCase(message) }<br>        }<br>        // Tray / banner presentation can remain Android-owned.<br>    }<br>}</pre><p>Android owns message delivery into the process. Shared Kotlin owns what that message means. Visible notification presentation can stay platform-specific because the operating system still controls how notifications are displayed. Feature code never needs to know about FirebaseMessagingService.</p><h3>Android Token Registration Has Two Paths</h3><p>Token registration is not limited to onNewToken(). The application also fetches the current token explicitly at lifecycle points such as login and session initialization:</p><pre>override suspend fun getNtfId(): String {<br>    return withTimeoutOrNull(FCM_TOKEN_TIMEOUT_MILLIS.milliseconds) {<br>        runCatching { FirebaseMessaging.getInstance().token.await() }<br>            .getOrDefault(&quot;&quot;)<br>    }.orEmpty()<br>}</pre><p>So Android effectively has:</p><pre>token refresh callback<br>        ↓<br>SetNotificationIdUseCase</pre><p>and:</p><pre>explicit current-token fetch<br>        ↓<br>DeviceInfoProvider.getNtfId()<br>        ↓<br>login / init request</pre><p>The callback handles token changes. The explicit fetch keeps the backend aligned at the moments a session begins. Both end in the same place: the backend knows the current FCM token.</p><h3>iOS: A Thin Swift Shell</h3><p>The same principle applies on iOS. The iOS host owns the platform mechanics around push registration. That includes:</p><ul><li>requesting notification authorization</li><li>registering for remote notifications</li><li>receiving the APNs device token</li><li>passing that token to Firebase Messaging</li><li>receiving the Firebase registration token</li><li>forwarding tokens and payloads into shared Kotlin</li></ul><p>The detail that matters is that iOS has two different tokens.</p><pre>APNs device token<br>    → Apple push identity<br><br>FCM registration token<br>    → Firebase Messaging identity</pre><p>They are not interchangeable.</p><h3>APNs Token First</h3><p>The initial registration path starts when iOS provides the application with the APNs device token.</p><pre>func application(<br>    _ application: UIApplication,<br>    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data<br>) {<br>    Messaging.messaging().apnsToken = deviceToken<br>}</pre><p>That token belongs to APNs. We do not send the raw APNs token to the courier backend as the application’s notification identifier. Firebase Messaging consumes the APNs token as part of its own registration process and produces the FCM registration token used by the product. Conceptually:</p><pre>iOS remote notification registration<br>      ↓<br>APNs device token<br>      ↓<br>Firebase Messaging<br>      ↓<br>FCM registration token</pre><h3>FCM Token Refresh on iOS</h3><p>Firebase can provide a refreshed token through MessagingDelegate.</p><pre>func messaging(<br>    _ messaging: Messaging,<br>    didReceiveRegistrationToken fcmToken: String?<br>) {<br>    guard let fcmToken, !fcmToken.isEmpty else { return }<br>    MainKt.handleFcmDeviceToken(token: fcmToken)<br>}</pre><p>This path handles token lifecycle changes without depending on a visible screen.</p><h3>Explicit FCM Token Fetch on iOS</h3><p>Just like Android, iOS also requests the current FCM token explicitly. This one lives in iosMain, as the iOS side of the same DeviceInfoProvider contract:</p><pre>override suspend fun getNtfId(): String {<br>    return withTimeoutOrNull(FCM_TOKEN_TIMEOUT_MILLIS.milliseconds) {<br>        runCatching {<br>            suspendCancellableCoroutine { continuation -&gt;<br>                FIRMessaging.messaging().tokenWithCompletion { token, _ -&gt;<br>                    if (continuation.isActive) {<br>                        continuation.resume(token.orEmpty())<br>                    }<br>                }<br>            }<br>        }.getOrDefault(&quot;&quot;)<br>    }.orEmpty()<br>}</pre><p>That gives iOS the same high-level model:</p><pre>FCM token refresh callback<br>          ↓<br>Kotlin bridge<br>          ↓<br>SetNotificationIdUseCase</pre><p>and:</p><pre>explicit current-token fetch<br>          ↓<br>DeviceInfoProvider.getNtfId()<br>          ↓<br>login / init request</pre><p>The platform APIs differ. The product path does not.</p><h3>The Kotlin Bridge Stays Small</h3><p>The Swift-to-Kotlin bridge should not become another business layer. It is one line:</p><pre>fun handleFcmDeviceToken(token: String) {<br>    IOSFcmInitializer.handleDeviceToken(token)<br>}</pre><p>The refresh path eventually converges on:</p><pre>setNotificationIdUseCase.once(token)</pre><p>So the complete path looks like:</p><pre>APNs token<br>      ↓<br>Firebase Messaging<br>      ↓<br>FCM token<br>      ↓<br>┌─────────────────────────┬─────────────────────────┐<br>│ refresh callback        │ explicit fetch          │<br>│        ↓                │        ↓                │<br>│ Kotlin bridge           │ getNtfId()              │<br>│        ↓                │        ↓                │<br>│ SetNotificationIdUseCase│ login / init request    │<br>└─────────────────────────┴─────────────────────────┘<br>      ↓<br>backend registration</pre><p>Swift owns the APNs handoff and the Firebase delegate callback. Shared Kotlin owns what the final FCM token means to the product.</p><h3>Push Payloads Follow the Same Boundary</h3><p>Payload delivery follows the same architecture. On iOS:</p><pre>notification payload<br>      ↓<br>Swift entry point<br>      ↓<br>MainKt.handleFcmNotification(...)<br>      ↓<br>parse<br>      ↓<br>toFcmMessage()<br>      ↓<br>HandleFcmMessageUseCase</pre><p>The platform receives the payload. Shared Kotlin interprets it. This keeps push behavior aligned with the same domain reactions used elsewhere in the app.</p><h3>The iOS Startup Race</h3><p>There is one practical issue worth calling out. A token callback or push payload can arrive before shared dependency injection has finished initializing. That means the bridge needs to tolerate early platform delivery. Conceptually:</p><pre>push / token arrives<br>      ↓<br>shared runtime not ready<br>      ↓<br>hold in memory<br>      ↓<br>shared DI becomes ready<br>      ↓<br>shared handler</pre><p>Explicit token fetching helps with this as well. The login and session-init requests carry the current FCM token, so backend registration does not rely only on an earlier callback. That coordination belongs to the platform host. It is not product behavior.</p><h3>Analytics: One Event Language, Multiple Providers</h3><p>Analytics has a similar dependency problem. Without a boundary, feature code gradually accumulates calls to:</p><pre>Firebase<br>Mixpanel<br>Braze<br>...</pre><p>At that point every product feature has to understand every analytics provider. We wanted the dependency direction to be the opposite. Feature and domain code emit through one shared API:</p><pre>AnalyticsManager.logEvent(name, properties)</pre><p>Conceptually:</p><pre>feature / domain<br>      ↓<br>AnalyticsManager<br>      ↓<br>AnalyticsProviderInterface<br>      ↓<br>Firebase / Mixpanel / Braze / ...</pre><p>Each provider implements the same contract:</p><pre>interface AnalyticsProviderInterface {<br>    val providerType: AnalyticsProvider<br>    fun initialize()<br>    fun logEvent(event: AnalyticsEvent)<br>    fun setUserProperty(property: UserProperty)<br>    fun removeUserProperty(key: String)<br>    fun setUserId(userId: String?)<br>    fun clearUserData()<br>    fun isInitialized(): Boolean<br>}</pre><p>The manager can centralize:</p><ul><li>default properties</li><li>common metadata</li><li>user identity</li><li>provider fan-out</li><li>provider-specific adaptation</li></ul><p>A feature needs to know:</p><pre>event name<br>properties<br>business context</pre><p>It does not need to know:</p><pre>Firebase API<br>Mixpanel API<br>Braze API<br>provider initialization</pre><p>Providers can change. The product event language should remain stable.</p><h3>Logging: One Shared Call Site</h3><p>Logging follows the same pattern. Shared code writes against one stable boundary:</p><pre>expect object PlatformLogger {<br>    fun log(tag: String, message: String, category: DiagnosticCategory? = null)<br>    fun shareLogFile()<br>}</pre><p>That gives common and feature code one logging API without spreading native logging calls through the codebase. Categories can still make logs easier to work with:</p><ul><li>HTTP</li><li>Socket</li><li>FCM</li><li>Geofence</li><li>Service</li></ul><p>The architecture looks like:</p><pre>shared feature code<br>      ↓<br>PlatformLogger<br>      ↓<br>Android / iOS logging implementation</pre><p>The call site remains stable. The platform implementation can evolve underneath it.</p><h3>Crash Reporting Is a Separate Boundary</h3><p>Operational logging and crash reporting overlap, but they solve different problems. Crash reporting therefore stays behind its own contract:</p><pre>expect class CrashlyticsManager() {<br>    fun log(message: String)<br>    fun recordException(throwable: Throwable)<br>    fun setUserId(userId: String)<br>    fun setCustomKey(key: String, value: String)<br>    fun setCustomKey(key: String, value: Boolean)<br>    fun setCustomKey(key: String, value: Int)<br>    fun setCustomKey(key: String, value: Long)<br>    fun setCustomKey(key: String, value: Double)<br>}</pre><p>Feature code can use that API to:</p><ul><li>add crash breadcrumbs</li><li>record non-fatal exceptions</li><li>associate user context</li><li>add structured metadata</li></ul><p>It does not need to understand the native Firebase Crashlytics API. Conceptually:</p><pre>PlatformLogger<br>    → operational logs<br><br>CrashlyticsManager<br>    → crashes<br>    → non-fatal exceptions<br>    → crash context</pre><p>Keeping those responsibilities separate made both APIs easier to follow.</p><h3>Android Crashlytics Implementation</h3><p>On Android, a Kotlin Throwable maps naturally into Firebase Crashlytics.</p><pre>actual class CrashlyticsManager actual constructor() {<br>    private val crashlytics: FirebaseCrashlytics by lazy {<br>        FirebaseCrashlytics.getInstance()<br>    }<br>    actual fun log(message: String) {<br>        crashlytics.log(message)<br>    }<br>    actual fun recordException(throwable: Throwable) {<br>        crashlytics.recordException(throwable)<br>    }<br>    actual fun setUserId(userId: String) {<br>        crashlytics.setUserId(userId)<br>    }<br>    actual fun setCustomKey(key: String, value: String) {<br>        crashlytics.setCustomKey(key, value)<br>    }<br>}</pre><p>The adaptation is almost direct:</p><pre>Kotlin Throwable<br>      ↓<br>FirebaseCrashlytics.recordException()</pre><p>Very little translation is required.</p><h3>iOS Crashlytics Implementation</h3><p>On iOS, the native Crashlytics API has a different error model. A Kotlin Throwable is not the same thing as an NSError. So the platform implementation adapts it.</p><pre>actual class CrashlyticsManager actual constructor() {<br>    private val crashlytics: FIRCrashlytics by lazy {<br>        FIRCrashlytics.crashlytics()<br>    }<br><br>    actual fun log(message: String) {<br>        crashlytics.log(message)<br>    }<br>    actual fun recordException(throwable: Throwable) {<br>        crashlytics.log(&quot;Exception: ${throwable.message ?: &quot;Unknown error&quot;}&quot;)<br>        crashlytics.log(&quot;Stack trace: ${throwable.stackTraceToString()}&quot;)<br>        val userInfo = mapOf&lt;Any?, Any?&gt;(<br>            &quot;message&quot; to (throwable.message ?: &quot;Unknown error&quot;),<br>            &quot;stackTrace&quot; to throwable.stackTraceToString(),<br>            &quot;exceptionType&quot; to throwable::class.simpleName,<br>        )<br>        val nsError = NSError.errorWithDomain(<br>            domain = &quot;com.getir.mdu.exception&quot;,<br>            code = -1,<br>            userInfo = userInfo,<br>        )<br>        crashlytics.recordError(nsError)<br>    }<br>    actual fun setUserId(userId: String) {<br>        crashlytics.setUserID(userId)<br>    }<br>    actual fun setCustomKey(key: String, value: String) {<br>        crashlytics.setCustomValue(value, key)<br>    }<br>}</pre><p>The iOS path therefore becomes:</p><pre>Kotlin Throwable<br>      ↓<br>message + Kotlin stack trace<br>      ↓<br>NSError adaptation<br>      ↓<br>FIRCrashlytics.recordError()</pre><p>The Kotlin exception details are also logged before the adapted NSError is recorded. That preserves useful Kotlin-side context while still working with the native Crashlytics API.</p><h3>Same Capability, Different Native Mechanics</h3><p>Android can do:</p><pre>Throwable<br>      ↓<br>recordException(Throwable)</pre><p>iOS does:</p><pre>Throwable<br>      ↓<br>message + stack trace<br>      ↓<br>NSError<br>      ↓<br>recordError(NSError)</pre><p>But shared code only sees:</p><pre>CrashlyticsManager.recordException(throwable)</pre><p>That is the boundary that mattered. We did not force both Firebase SDKs into identical native behavior. We exposed one product capability and adapted each platform underneath it.</p><h3>Lifecycle: Session State Controls Service Lifetime</h3><p>Part 7 covered what MduBackgroundService owns. Here, the relevant part is only the lifecycle glue around it. AppLifecycleManager observes authenticated session state and courier identity. Conceptually:</p><pre>logged in + courier available<br>      ↓<br>remote-config synchronization launched<br>      ↓<br>MduBackgroundService.start(courierId)</pre><p>And:</p><pre>logged out / no courier<br>      ↓<br>MduBackgroundService.stop()</pre><p>A simplified shape:</p><pre>class AppLifecycleManager(<br>    private val backgroundService: MduBackgroundService,<br>) {<br>    fun init() {<br>        // Observe authenticated state.<br>        // Observe courierId.<br>        // Start or stop session service.<br>    }<br>}</pre><p>The manager is initialized from the platform host on Android and iOS. Screens still do not own the operational stack. Lifecycle answers one question:</p><pre>Does an authenticated courier session currently exist?</pre><p>If yes, the operational service should exist. If no, it should stop. Lifecycle does not decide:</p><ul><li>socket survival behavior</li><li>telemetry batching</li><li>GPS backfill policy</li><li>platform background execution</li><li>how location is acquired</li></ul><p>Those responsibilities already live behind the service and platform boundaries established earlier in the series.</p><h3>What These Edges Have in Common</h3><p>Push, analytics, logging, crash reporting, and lifecycle solve different problems. Architecturally, they follow the same shape:</p><pre>OS / vendor API<br>      ↓<br>thin platform implementation<br>      ↓<br>shared Kotlin contract<br>      ↓<br>product behavior</pre><p>We did not rewrite Firebase inside commonMain. We did not make Mixpanel a domain dependency. We did not model Android and iOS push delivery as if the operating systems behaved the same. We did not force two Crashlytics SDKs into one artificial identical native implementation.</p><p>Instead, we made those capabilities reachable from shared Kotlin without letting implementation details spread into every feature. That is a better goal than maximizing shared code for its own sake.</p><h3>Dual Maintenance Still Exists at the Product Shell</h3><p>Facades reduce product drift. They do not eliminate platform verification.</p><p>If the push contract changes:</p><ul><li>Android intake needs testing</li><li>iOS intake needs testing</li></ul><p>If analytics events change:</p><ul><li>provider adapters still need verification</li></ul><p>If logging contracts change:</p><ul><li>Android and iOS implementations need review</li></ul><p>If crash metadata changes:</p><ul><li>both Crashlytics implementations need validation</li></ul><p>If lifecycle start conditions change:</p><ul><li>both application hosts need verification</li></ul><p>KMP moves product meaning into shared Kotlin. It does not remove Android and iOS. The platform surface becomes smaller and more explicit. That is the boundary doing its job.</p><h3>What Platform Edges Changed for Us</h3><p>Part 7 established ownership of the courier session. Part 8 described the operational programs running inside it. Part 9 closes the remaining platform boundaries around that shared product.</p><p>Push enters through different operating-system doors but converges into shared Kotlin. On iOS:</p><pre>APNs<br>      ↓<br>Firebase Messaging<br>      ↓<br>FCM token<br>      ↓<br>refresh callback → Kotlin bridge → SetNotificationIdUseCase<br>explicit fetch   → getNtfId()    → login / init request</pre><p>On Android:</p><pre>FCM token<br>      ↓<br>onNewToken     → SetNotificationIdUseCase<br>explicit fetch → getNtfId() → login / init request</pre><p>Analytics speaks one product event language to multiple providers. Logging exposes one stable product-facing API. Crash reporting exposes one shared capability while allowing native exception handling to differ:</p><pre>commonMain<br>CrashlyticsManager<br>      ↓<br>Android:  Throwable → Firebase<br>iOS:      Throwable → NSError → Firebase</pre><p>Lifecycle connects authenticated session state to the background-service layer without making screens responsible for operational infrastructure.</p><p>The goal was never to eliminate platform code. It was to contain it. Vendor SDKs remain at the edge. Shared Kotlin remains the product layer.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-10-the-playbook-what-we-would-repeat-what-we-would-not-6a68628cb06f">Part 10</a> turns the migration into a reusable playbook.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8854c42992" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-9-platform-edges-facades-around-the-product-shell-ef8854c42992">Part 9 — Platform Edges: Facades Around the Product Shell</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 8 — Realtime + Telemetry: Session Behavior, Not Screen Accidents]]></title>
            <link>https://medium.com/getir/part-8-realtime-telemetry-session-behavior-not-screen-accidents-b9427aba1494?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/b9427aba1494</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:14:30 GMT</pubDate>
            <atom:updated>2026-11-16T11:08:18.195Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEpaPEGeyMMFUkOhTrLB7g.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 8 of 11</em></p><p><a href="https://medium.com/getir/part-7-background-service-one-scope-many-handlers-two-hosts-a7d85f64011c">Part 7</a> established who owns the operational lifetime:</p><pre>One service<br>      ↓<br>Many handlers<br>      ↓<br>One session CoroutineScope<br>      ↓<br>Two platform hosts</pre><p>Part 8 looks at what actually runs inside that lifetime:</p><ul><li>realtime communication</li><li>software geofencing</li><li>GPilot telemetry</li><li>GPS backfill</li></ul><p>These systems are easy to dismiss as “background features,” but that undersells them in a courier app. They are part of the courier session. They should not depend on HomeScreen being visible, a specific ViewModel staying alive, or a particular destination remaining in the NavHost.</p><p>The screen observes the operation. It does not own it.</p><h3>The Session Is the Execution Boundary</h3><p>Once a courier session starts, the shared operational stack looks roughly like this:</p><pre>MduBackgroundService<br>│<br>├── LocationManager / SensorManager / ...<br>│<br>├── SocketHandler<br>├── SoundHandler<br>├── GeofenceHandler<br>├── GPilotHandler<br>├── GPilotOldHandler<br>└── BackfillGpsHandler</pre><p>Part 5 fenced the device SDKs. Part 7 established session lifetime. This part is about the programs that run on top of those boundaries.</p><p>A socket event should not need a visible Composable to matter. A geofence transition should not depend on a ViewModel remaining in the navigation stack. Telemetry should not begin because a screen entered composition. The session is the execution boundary.</p><h3>SocketHandler: Realtime While the Channel Exists</h3><p>SocketHandler owns realtime connection policy for the courier session. Its responsibilities include:</p><ul><li>deciding when to connect</li><li>observing connection configuration</li><li>registering business listeners</li><li>coordinating work that depends on the realtime channel</li><li>disconnecting when the session ends</li></ul><p>It does not own operating-system process survival. Underneath it sits a transport abstraction:</p><pre>interface SocketClient {<br>    val connectionState: StateFlow&lt;SocketConnectionState&gt;<br>    suspend fun connect(url: String, token: String, deviceId: String)<br>    suspend fun disconnect()<br>    suspend fun emit(event: String, data: String)<br>    fun on(event: String, callback: (String) -&gt; Unit)<br>    fun off(event: String)<br>    suspend fun cleanup()<br>}</pre><p>commonMain owns the connection policy. Android and iOS provide their own Socket.IO implementations behind this interface. A simplified lifecycle looks like:</p><pre>start()<br>      ↓<br>observe socket configuration<br>      ↓<br>connect with session credentials<br>      ↓<br>register business listeners<br>      ↓<br>start realtime-dependent work<br>      ↓<br>observe connection health<br>      ↓<br>recover when the channel becomes unusable</pre><p>And eventually:</p><pre>stop()<br>      ↓<br>unregister listeners<br>      ↓<br>disconnect</pre><p>The realtime pipe has two directions.</p><p><strong>Outbound.</strong> While the channel is available, data such as current location can be emitted through it.</p><p><strong>Inbound.</strong> Operational events arrive through the same channel and are translated into domain behavior, not directly into UI callbacks. The direction is:</p><pre>realtime event<br>      ↓<br>domain behavior<br>      ↓<br>product state changes<br>      ↓<br>UI observes the result</pre><p>That keeps the socket attached to the courier session rather than to a screen.</p><h3>Realtime Transport Has a Boundary</h3><p>One rule from Part 7 still applies: a socket is a realtime channel. It is not guaranteed background transport for location. When the operating system no longer gives us a reliable socket lifetime, location continuity cannot mean “pretend the socket is still alive.” That capability needs its own delivery path.</p><h3>Background Location Is Not Socket Continuity</h3><p>The realtime flow looks like this:</p><pre>courier session active<br>      ↓<br>socket connected<br>      ↓<br>location out<br>business events in</pre><p>The background-location path is different:</p><pre>background location available<br>      ↓<br>OS delivers location updates<br>      ↓<br>shared session receives location<br>      ↓<br>location is delivered to backend</pre><p>These are related concerns, but they do not share the same transport lifetime. The rule we use is:</p><pre>socket available<br>      ↓<br>use realtime communication</pre><p>while:</p><pre>background location available<br>      ↓<br>deliver location without assuming socket lifetime</pre><p>This distinction matters especially on iOS, where the app does not control socket lifetime the way it controls normal foreground execution. The product requirement stays the same. The transport can change.</p><h3>One Swift Bridge, and Why There Is Only One</h3><p>On iOS, the SocketClient implementation needed one extra step. The Socket.IO iOS client exposes a Swift-only API, which Kotlin/Native cannot call directly. So we placed a small Swift package in front of it that exposes a minimal @objc surface: connect, disconnect, emit, and a delegate for events and state changes, with payloads passed across as JSON strings.</p><pre>@objc public protocol SocketIOKotlinClientDelegate: AnyObject {<br>    func socketClient(_ client: SocketIOKotlinClient, didReceiveEvent event: String, dataJson: String)<br>    func socketClient(_ client: SocketIOKotlinClient, didChangeState state: String, attempt: Int)<br>}<br>@objc public class SocketIOKotlinClient: NSObject {<br>    @objc public weak var delegate: SocketIOKotlinClientDelegate?<br>    @objc(connectWithUrl:token:deviceId:enableLog:)<br>    public func connect(url: String, token: String, deviceId: String, enableLog: Bool)<br>    @objc public func disconnect()<br>    @objc(emitWithEvent:jsonData:)<br>    public func emit(event: String, jsonData: String)<br>    @objc public func on(event: String)<br>    @objc public func off(event: String)<br>}</pre><p>The shared module imports that package directly through Gradle’s Swift Package Manager integration:</p><pre>swiftPMDependencies {<br>    localSwiftPackage(<br>        directory = rootProject.layout.projectDirectory.dir(&quot;socket-io-kotlin-bridge&quot;),<br>        products = listOf(&quot;SocketIOKotlinBridge&quot;),<br>    )<br>}</pre><p>On the Kotlin side, IOSSocketClient implements the shared SocketClient interface and talks only to that bridge:</p><pre>class IOSSocketClient : SocketClient {<br>    private var bridge: SocketIOKotlinClient? = null<br>    override suspend fun connect(url: String, token: String, deviceId: String) {<br>        val client = SocketIOKotlinClient().also { bridge = it }<br>        client.setDelegate(bridgeDelegate)<br>        client.connectWithUrl(url = url, token = token, deviceId = deviceId, enableLog = AppConfig.IS_DEBUG)<br>    }<br>    override suspend fun emit(event: String, data: String) {<br>        bridge?.emitWithEvent(event, jsonData = data)<br>    }<br>    private fun handleStateChange(state: String, attempt: Int) {<br>        _connectionState.value = when (state) {<br>            &quot;connected&quot; -&gt; SocketConnectionState.Connected(now())<br>            &quot;disconnected&quot; -&gt; SocketConnectionState.Disconnected<br>            &quot;reconnecting&quot; -&gt; SocketConnectionState.Reconnecting(attempt)<br>            else -&gt; /* error signals */ ...<br>        }<br>    }<br>}</pre><p>Everything above SocketClient (connection policy, listeners, recovery) stays in shared Kotlin. The bridge has no business logic of its own: it translates calls, nothing more.</p><p>It is also the only bridge of its kind in the app. Every other native SDK we use (Firebase Core, Analytics, Crashlytics and Messaging, Google Maps, ML Kit barcode scanning, Mixpanel, and Braze) exposes an Objective-C-compatible API. Kotlin/Native calls those directly from iosMain through the same SPM import, just like Apple frameworks such as CoreLocation, AVFoundation, and CoreMotion. Where we had a choice, we picked the variant that keeps it that way: for Mixpanel, we use the Objective-C mixpanel-iphone SDK rather than the pure-Swift mixpanel-swift. Socket.IO&#39;s iOS client gave us no such option. Its v16 API is Swift-only, so it got the bridge.</p><p>The rest of the Swift in the app is the shell itself: app entry, APNs registration, and notification callbacks that hand off to Kotlin. Bridge and shell together come to under 500 lines.</p><h3>GeofenceHandler: Product Rules on the Location Stream</h3><p>GeofenceHandler owns task-driven software geofencing for the active courier session. It observes:</p><ul><li>the current task</li><li>relevant geofence definitions</li><li>location updates from the shared LocationManager</li></ul><p>and evaluates transitions in shared Kotlin. Conceptually:</p><pre>current task<br>      ↓<br>active geofences<br>      ↓<br>LocationManager.unthrottledLocation<br>      ↓<br>GeofenceTriggerProcessor<br>      ↓<br>ENTER / EXIT / DWELL<br>      ↓<br>domain behavior</pre><p>These transitions are product concepts.</p><p><strong>ENTER.</strong> The courier moves inside the geofence according to the configured distance and accuracy rules.</p><p><strong>EXIT.</strong> The courier moves outside under the corresponding rules.</p><p><strong>DWELL.</strong> The courier remains inside long enough for the transition to become meaningful. DWELL is not one lucky GPS sample inside a radius. It is a timed evaluation over the location stream.</p><p>That is why this behavior belongs in shared product logic rather than being defined independently by each platform SDK.</p><h3>Software Geofencing and Native Geofencing Are Different Paths</h3><p>Part 5 introduced two valid geofence mechanisms. Software geofencing:</p><pre>shared LocationManager<br>      ↓<br>shared Kotlin evaluation<br>      ↓<br>ENTER / EXIT / DWELL</pre><p>Native geofencing:</p><pre>OS region APIs<br>      ↓<br>PlatformGeofenceManager<br>      ↓<br>platform geofence events</pre><p>They solve related problems, but they are not the same mechanism. GeofenceHandler uses the shared software path where product consistency matters. Native geofencing remains available where OS-level region monitoring is useful. What we avoid is collapsing them into one abstraction just because both contain the word &quot;geofence.&quot;</p><h3>GPilot: Telemetry as a Pipeline</h3><p>GPilot is not a screen feature. It is a session telemetry pipeline. In short:</p><pre>sensors + GPS + device context<br>      ↓<br>in-memory buffers<br>      ↓<br>local persistence<br>      ↓<br>upload when transport and auth allow</pre><p>Collection and delivery are intentionally decoupled. A sensor sample existing does not mean it should immediately become a network request. The telemetry pipeline can:</p><ul><li>collect</li><li>buffer</li><li>group</li><li>persist</li><li>upload</li><li>retry or drain later</li></ul><p>according to its own policy. That gives telemetry a lifetime and failure model independent of the UI.</p><h3>GPilotHandler: Continuous Telemetry</h3><p>The newer pipeline follows courier-session lifetime. Conceptually:</p><pre>session starts<br>      ↓<br>continuous collection<br>      ↓<br>time-based chunks<br>      ↓<br>rotate / close chunk<br>      ↓<br>persist<br>      ↓<br>upload closed work<br>      ↓<br>clean up delivered data</pre><p>The persistence boundary is the chunk. A screen does not decide when a chunk opens or closes. The handler does. That matters because telemetry continuity should not change when the courier navigates from Home to Delivery or back again.</p><pre>session starts<br>      ↓<br>handler owns collection<br>      ↓<br>handler owns buffers<br>      ↓<br>handler owns persistence boundary<br>      ↓<br>handler owns upload policy<br>      ↓<br>UI owns none of it</pre><p>Sensor and GPS data already arrive through the platform edges from Part 5:</p><pre>SensorManager<br>LocationManager</pre><p>By the time GPilot sees them, those values have already been normalized into shared models. That keeps telemetry logic independent from Android SensorEvent, Core Motion types, or native location objects. We also keep legacy trip telemetry and continuous telemetry separate while both are operationally required.</p><h3>BackfillGpsHandler: The Safety Net Under Realtime</h3><p>Realtime location delivery can fail for normal reasons:</p><ul><li>socket disconnected</li><li>network unavailable</li><li>temporary transport failure</li></ul><p>Those gaps should not silently become missing operational history. That is where GPS backfill comes in. Conceptually:</p><pre>courier session active<br>      ↓<br>realtime delivery unavailable<br>      ↓<br>persist location locally</pre><p>When delivery becomes possible again:</p><pre>transport available<br>      ↓<br>read pending backfill<br>      ↓<br>send<br>      ↓<br>delete successfully delivered data</pre><p>Backfill is a continuity mechanism. It is not another source of location. LocationManager remains the source. Realtime is one delivery path. Backfill preserves data when that path cannot deliver.</p><h3>Backfill Is Not Background Endpoint Delivery</h3><p>There is another distinction that matters. Background endpoint delivery answers:</p><pre>How do we deliver the current location<br>when socket lifetime is not a safe assumption?</pre><p>Backfill answers:</p><pre>What happens when delivery fails and<br>location must survive locally until recovery?</pre><p>Those are different failure modes. Conceptually:</p><pre>Background endpoint delivery<br>      ↓<br>deliver current location without depending on socket</pre><p>versus:</p><pre>Backfill<br>      ↓<br>persist undelivered location<br>      ↓<br>drain later</pre><p>Keeping those concepts separate stops “offline,” “background,” and “socket disconnected” from collapsing into one overloaded state.</p><p><strong>Continuity does not mean keeping one transport alive forever.</strong> It means preserving the operation when that transport is no longer available.</p><h3>One Session Scope Owns the Operational Set</h3><p>Every handler in this part still follows the ownership model from Part 7. The service creates the session scope:</p><pre>val scope = CoroutineScope(SupervisorJob() + dispatchers.io)</pre><p>Handlers receive it:</p><pre>socketHandler = get { parametersOf(scope) }<br>geofenceHandler = get { parametersOf(scope) }<br>gpilotHandler = get { parametersOf(scope) }<br>backfillGpsHandler = get { parametersOf(socketHandler, scope) }</pre><p>When the session is cancelled:</p><pre>session cancelled<br>      ↓<br>socket observers stop<br>geofence collectors stop<br>DWELL timers stop<br>telemetry collectors stop<br>backfill collectors stop</pre><p>This is what keeps navigation from becoming an accidental lifetime boundary. If those loops were screen-owned, leaving a destination could stop operational behavior. If every handler created an independent forever-scope, logout would no longer guarantee cleanup. One session scope keeps the model explicit.</p><h3>What Is Shared and What Stays at the Edge</h3><p>The boundary is now fairly clear.</p><h3>Shared in commonMain</h3><ul><li>SocketHandler connection policy</li><li>business-event wiring</li><li>software geofence evaluation</li><li>GPilot collection policy</li><li>GPilot persistence policy</li><li>GPS backfill persist-and-drain behavior</li><li>domain use cases triggered by realtime events</li></ul><h3>Platform-owned</h3><ul><li>SocketClient implementations</li><li>OS location acquisition</li><li>OS sensor acquisition</li><li>native geofence APIs</li><li>Android and iOS background hosts</li></ul><p>The product meaning of:</p><pre>courier is connected</pre><p>can remain shared. The Socket.IO implementation does not need to. Likewise:</p><pre>ENTER<br>EXIT<br>DWELL</pre><p>can remain shared product concepts. The platform GPS stack does not need to. That is the same rule used throughout the migration: share the decision, fence the mechanism.</p><h3>Dual Maintenance Still Exists</h3><p>Shared handlers reduce business-logic divergence. They do not remove platform QA.</p><p>If reconnect policy changes:</p><ul><li>shared socket policy changes</li><li>Android transport still needs verification</li><li>iOS transport still needs verification</li></ul><p>If software geofence thresholds change:</p><ul><li>shared geofence evaluation changes</li><li>both location pipelines still need validation</li></ul><p>If telemetry chunking changes:</p><ul><li>persistence and upload behavior need retesting on both platforms</li></ul><p>If backfill drain behavior changes:</p><ul><li>offline-to-online recovery needs retesting</li></ul><p>If iOS background location delivery changes:</p><ul><li>that iOS path needs validation</li></ul><p>If Android foreground-service requirements change:</p><ul><li>Android changes</li><li>iOS does not</li></ul><p>That is the intended split:</p><pre>shared operational programs<br>        ↓<br>platform transport and host mechanics</pre><p>Multiplatform removes duplicated product policy. It does not remove platform reality.</p><h3>What We Kept Separate</h3><p>A large part of this architecture is about refusing false equivalences. We kept these concepts separate:</p><pre>socket lifetime              ≠  background location lifetime<br>NavHost visibility           ≠  session connectivity<br>software geofencing          ≠  native OS geofencing<br>backfill                     ≠  another location source<br>background endpoint delivery ≠  GPS backfill</pre><p>These distinctions may look verbose in architecture diagrams. In production they represent different lifetimes, failure modes, and recovery paths. Merging them would make the system harder to follow.</p><h3>What Realtime + Telemetry Changed for Us</h3><p>Part 7 made lifetime ownership explicit. Part 8 makes the programs inside that lifetime explicit.</p><pre>Socket<br>      ↓<br>realtime session communication</pre><pre>Software geofencing<br>      ↓<br>product evaluation on location</pre><pre>GPilot<br>      ↓<br>buffered telemetry pipeline</pre><pre>GPS backfill<br>      ↓<br>continuity after delivery failure</pre><p>The key boundary is that realtime and continuity are not the same thing. The socket gives us a realtime channel while it exists. Background location can use another delivery path when socket lifetime is not available. Backfill preserves location when delivery itself fails.</p><p>Those are three different responsibilities. Keeping them separate lets the same courier session stay coherent on Android and iOS without turning screens into hidden service owners.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-9-platform-edges-facades-around-the-product-shell-ef8854c42992">Part 9</a> moves outward from the session and into the remaining platform-facing integrations around the product shell.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9427aba1494" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-8-realtime-telemetry-session-behavior-not-screen-accidents-b9427aba1494">Part 8 — Realtime + Telemetry: Session Behavior, Not Screen Accidents</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 7 — Background Service: One Scope, Many Handlers, Two Hosts]]></title>
            <link>https://medium.com/getir/part-7-background-service-one-scope-many-handlers-two-hosts-a7d85f64011c?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/a7d85f64011c</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:14:08 GMT</pubDate>
            <atom:updated>2026-11-16T11:11:25.424Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rD0A154r1QoDUDTrb4X_pg.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 7 of 11</em></p><p>Parts 1 through <a href="https://medium.com/getir/part-6-permissions-the-edge-that-unlocks-every-other-edge-d554b281e4ef">part 6</a> moved more of the application into shared Kotlin: infrastructure, presenters, navigation, device integrations, and permission policy. Part 7 is about the part of the courier app that still has to work when none of those screens are visible.</p><p>A courier app can look fine while the UI is open and still fail operationally if:</p><ul><li>the realtime connection disappears when Home leaves the foreground</li><li>telemetry stops when the device is locked</li><li>geofence evaluation depends on a ViewModel staying alive</li><li>GPS backfill has no owner during recoverable connectivity loss</li><li>long-running handlers survive logout because nothing explicitly owns their lifetime</li></ul><p>So the problem is not how to keep Compose alive in the background. The problem is deciding who owns the courier session when the UI is no longer what keeps the application alive.</p><p>Our answer was a session-owned background service coordinating multiple handlers under one CoroutineScope. Android and iOS host that session differently. The session itself stays shared.</p><h3>The UI Does Not Own the Operation</h3><p>Compose Multiplatform helped us share screens. It did not turn courier operations into screen-scoped work. MDU has several responsibilities that need to continue independently of the current destination:</p><ul><li>realtime communication</li><li>task alert sound</li><li>geofence evaluation</li><li>GPilot telemetry</li><li>legacy telemetry continuity where still required</li><li>GPS backfill during recoverable connectivity loss</li></ul><p>Those concerns outlive:</p><pre>LoginScreen<br>HomeScreen<br>DeliveryScreen<br>any single NavHost destination</pre><p>If a screen creates one of these handlers, the handler lifetime becomes tied to navigation. That is usually the wrong lifetime.</p><p>A courier can leave DeliveryScreen and still be on an active shift. A courier can move between Home, Go, Delivery, and other flows while the same realtime and telemetry session continues underneath. So we moved ownership off screens and onto the courier session itself.</p><h3>One Service Coordinates the Session</h3><p>At the top level, the architecture stays intentionally small:</p><pre>AppLifecycleManager<br>        ↓<br>MduBackgroundService<br>        ↓<br>Handlers + device managers</pre><p>The service coordinates handlers such as:</p><pre>MduBackgroundService<br>├── SocketHandler<br>├── SoundHandler<br>├── GeofenceHandler<br>├── GPilotHandler<br>├── GPilotOldHandler<br>└── BackfillGpsHandler</pre><p>Alongside them, it owns the device-facing managers that feed those handlers:</p><pre>LocationManager<br>SensorManager<br>BatteryManager<br>ActivityRecognitionManager</pre><p>Ownership is what matters here. The service creates the operational stack when the courier session starts and tears it down when that session ends. A simplified startup sequence looks like this:</p><pre>start managers<br>      ↓<br>start socket<br>      ↓<br>start sound<br>      ↓<br>start geofence<br>      ↓<br>start GPilot<br>      ↓<br>start legacy GPilot<br>      ↓<br>start GPS backfill</pre><p>The order is deliberate. For example, backfill recovery may depend on communication state already being available. Just as permission order was product policy in Part 6, startup order here is part of how the courier session behaves.</p><h3>One Session, One CoroutineScope</h3><p>Lifetime ownership is the core of this layer. The session creates one scope:</p><pre>val scope = CoroutineScope(SupervisorJob() + dispatchers.io)</pre><p>Session handlers receive that scope when they are created:</p><pre>socketHandler = get { parametersOf(scope) }<br>soundHandler = get { parametersOf(scope) }<br>geofenceHandler = get { parametersOf(scope) }<br>gpilotHandler = get { parametersOf(scope) }<br>gpilotOldHandler = get { parametersOf(scope) }<br>backfillGpsHandler = get { parametersOf(socketHandler, scope) }</pre><p>Koin is not the point of this example. What matters is that the service owns the scope and the handlers borrow it. The handlers do not create independent application-lifetime scopes for themselves. That gives us a clear ownership chain:</p><pre>courier session<br>      ↓<br>MduBackgroundService<br>      ↓<br>session CoroutineScope<br>      ↓<br>handlers</pre><p>When the session ends, the owner is known.</p><h3>Why One Scope Matters</h3><p>With one explicit session scope:</p><ul><li>one cancellation can terminate session work</li><li>long-running collectors have a known owner</li><li>screens cannot accidentally keep operational work alive</li><li>logout has a deterministic cleanup path</li><li>tests can reason about lifetime</li><li>Android and iOS can use the same Kotlin ownership model</li></ul><p>The opposite pattern is much harder to control:</p><pre>single {<br>    SocketHandler(CoroutineScope(SupervisorJob()))<br>}</pre><p>Now SocketHandler has created its own lifetime. That immediately raises questions. Who cancels it? Does logout stop it? Does replacing the service stop it? Can the coroutine continue after the courier session has ended? If those answers are unclear, the lifetime model is already leaking.</p><p>For session-scoped work, we prefer factories that receive the service-owned scope instead of process-lifetime singletons that create scopes internally. Stopping the session then becomes predictable:</p><pre>stop handlers and managers<br>      ↓<br>cancel session scope<br>      ↓<br>release references</pre><p>The operational stack leaves with the courier session.</p><p><strong>Every long-running lifetime needs an owner.</strong> If a coroutine, handler, socket, or sensor stream can outlive the object that created it without an explicit owner, the session becomes hard to control.</p><h3>Shared Contract, Different Hosts</h3><p>The shared service contract stays intentionally small:</p><pre>interface MduBackgroundService {<br>    suspend fun start(courierId: String)<br>    suspend fun stop()<br>    fun isRunning(): Boolean<br>}</pre><p>Creation remains platform-specific:</p><pre>expect fun createMduBackgroundService(): MduBackgroundService</pre><p>Common code owns:</p><ul><li>which handlers participate in the courier session</li><li>handler startup order</li><li>session-scope ownership</li><li>when the session starts</li><li>when the session stops</li></ul><p>Platform code owns:</p><ul><li>how the operating system hosts that session</li><li>background-execution requirements</li><li>platform lifecycle integration</li><li>notifications or background modes</li><li>host recovery behavior</li></ul><p>This is the same boundary we used for maps, camera, location, and sensors in Part 5. Product behavior stays shared. Operating-system mechanics stay native.</p><h3>Android: A Thin Foreground Shell Around Shared Work</h3><p>Android gives us a foreground-service primitive. That does not mean the entire courier session should live inside one large Android Service class. We keep session orchestration separate from the Android host. Conceptually:</p><pre>AndroidMduBackgroundService<br>├── owns session scope<br>├── owns shared handlers<br>├── owns managers<br>└── owns session start / stop</pre><p>while:</p><pre>MduForegroundService<br>├── owns Android foreground shell<br>├── notification<br>├── startForeground(...)<br>└── platform lifecycle / recovery behavior</pre><p>That separation matters. The Android foreground service exists because the OS needs a visible background-execution contract for certain workloads. It should not become the place where courier business logic accumulates.</p><p>Foreground-service types reflect the work being hosted, including capabilities such as:</p><pre>location<br>media playback</pre><p>Location supports GPS-driven operational work. Media playback supports task-alert audio where required. In short:</p><pre>courier session starts<br>        ↓<br>Android foreground shell starts<br>        ↓<br>shared service starts managers + handlers<br>        ↓<br>Android keeps the active workload visible to the OS</pre><p>Stopping looks like this:</p><pre>stop Android foreground shell<br>        ↓<br>stop handlers and managers<br>        ↓<br>cancel session scope</pre><p>Android may also need recovery behavior if the platform host disappears while product state still says the courier session is active. That recovery stays Android-owned. The shared handlers do not fork into Android-specific versions just because the OS uses a foreground-service model.</p><h3>iOS: The Same Session Under Different Background Rules</h3><p>iOS does not have an Android ForegroundService. We did not pretend otherwise. IOSMduBackgroundService can still own the same Kotlin session. It can still:</p><ul><li>create the session scope</li><li>create the handlers</li><li>start device managers</li><li>coordinate startup order</li><li>stop the session explicitly</li></ul><p>What changes is how the operating system lets individual capabilities continue once the UI is no longer active. That is where the iOS host diverges from Android. One distinction matters a lot: realtime communication and background location are not the same transport problem.</p><h3>Realtime Communication Is Not the Background Location Transport</h3><p>While the communication channel is available, the socket remains the realtime path. But we do not treat a living socket as guaranteed background transport on iOS. That lifetime is not fully controlled by the application.</p><p>If background location still needs to reach the backend while the UI is gone, location delivery needs a path that does not depend on the socket remaining alive. Conceptually:</p><pre>background location authorization<br>        ↓<br>OS delivers location updates<br>        ↓<br>shared session receives location<br>        ↓<br>location is delivered to backend</pre><p>That is different from:</p><pre>Socket<br>    ↓<br>realtime communication<br>while the channel is available</pre><p>The distinction is important because otherwise two unrelated lifetimes become coupled:</p><pre>socket alive<br>        ↓<br>location can be delivered</pre><p>That is too fragile for a background location requirement. Instead:</p><pre>background location available<br>        ↓<br>session receives location<br>        ↓<br>backend delivery uses its own path</pre><p>The product requirement stays the same: the courier’s location needs to be delivered. The transport can change depending on the background capability and OS constraints.</p><h3>Same Session, Different Host</h3><p>At the architecture level:</p><pre>Android<br>foreground-service host<br>        ↓<br>shared Kotlin session</pre><p>and:</p><pre>iOS<br>platform background capabilities<br>        ↓<br>shared Kotlin session<br>        ↓<br>background location can use<br>independent backend delivery</pre><p>The SocketHandler is still the same product concept. The GeofenceHandler does not become a second native implementation. GPilot does not become a separate Swift rewrite. The host changes. A specific background capability may use a different transport. The shared session semantics stay the same.</p><h3>The Service Is a Session Coordinator, Not a Container for Everything</h3><p>Not every object that can run while no screen is visible belongs inside MduBackgroundService. That boundary matters. Work that belongs to the courier session can include:</p><pre>socket<br>sound<br>geofence<br>GPilot<br>GPS backfill<br>session-scoped device managers</pre><p>These responsibilities have roughly the same lifetime:</p><pre>courier logs in<br>        ↓<br>session exists<br>        ↓<br>work continues<br>        ↓<br>courier logs out<br>        ↓<br>work stops</pre><p>Other work may have a completely different lifetime. Examples include:</p><pre>app-level remote config<br>independent diagnostic monitors<br>process-lifetime infrastructure<br>UI-scoped work</pre><p>Whether something runs “in the background” is not enough to decide where it belongs. What matters is whether it shares the courier-session lifetime. If it does not, putting it in the service weakens ownership rather than improving it. Otherwise the background service slowly turns into a god object holding every long-lived coroutine in the app. That is exactly what we wanted to avoid.</p><h3>Login Starts the Session. Logout Stops It.</h3><p>The background service does not start because a Composable becomes visible. It starts because product state says there is an active courier session. Conceptually:</p><pre>login / session ready<br>        ↓<br>AppLifecycleManager<br>        ↓<br>backgroundService.start(courierId)</pre><p>And:</p><pre>logout / session invalid<br>        ↓<br>AppLifecycleManager<br>        ↓<br>backgroundService.stop()</pre><p>This separates operational lifetime from navigation lifetime. Once the session ends, its handlers should not keep running just because a singleton or unmanaged coroutine still exists. That is why startup and shutdown are tied to session state, not screen visibility.</p><h3>Session Lifetime and Screen Lifetime Are Different</h3><p>A screen has a relatively short lifecycle:</p><pre>enter destination<br>      ↓<br>compose<br>      ↓<br>collect presenter state<br>      ↓<br>leave destination<br>      ↓<br>screen disappears</pre><p>The courier session is much longer:</p><pre>courier logs in<br>      ↓<br>session starts<br>      ↓<br>Home<br>      ↓<br>GoTask<br>      ↓<br>Delivery<br>      ↓<br>other flows<br>      ↓<br>courier logs out<br>      ↓<br>session stops</pre><p>These are different lifetimes. Attaching socket connectivity, geofencing, telemetry, or GPS backfill to screen lifecycle would make operational continuity depend on navigation behavior. They belong to the courier-session lifecycle instead.</p><p>That also keeps the ownership boundaries from earlier parts of the migration clear. SharedNavigation owns destination movement. MduBackgroundService owns session continuity. Neither needs to own the other.</p><h3>Dual Maintenance Still Exists at the Service Edge</h3><p>Moving orchestration into shared Kotlin reduces product divergence. It does not eliminate platform validation.</p><p>If socket reconnect behavior changes, the shared handler may change, and both Android and iOS session lifecycles still need verification. If alert-sound behavior changes, both platforms still need validation. If geofence behavior changes, the device integrations from Part 5 still need to behave correctly. If background location delivery changes, Android foreground location and iOS background delivery still need validation. If Android foreground-service requirements change, Android changes and iOS does not.</p><p>That asymmetry is expected. The migration moved business orchestration into shared handlers. It did not move operating-system survival mechanics into common code.</p><h3>What We Chose Not to Share</h3><p>Some abstractions look neat but hide the wrong things.</p><pre>iOS has Android ForegroundService                  ❌<br>process-survival mechanics belong in commonMain    ❌<br>NavHost owns courier-session lifetime              ❌</pre><p>The shared part is:</p><pre>session<br>handlers<br>startup order<br>scope ownership<br>product lifetime</pre><p>The platform-specific part is how the operating system keeps that work alive. We also avoided forcing every background capability through one transport just because that transport works while the app is active. A socket and background location do not need identical lifetime semantics. Keeping that distinction explicit makes the architecture easier to follow.</p><h3>What Background Service Changed for Us</h3><p>Shared UI made the application visible on both platforms. The background-service layer made the courier session independent of the currently visible screen. The ownership model became:</p><pre>One courier session<br>        ↓<br>One MduBackgroundService<br>        ↓<br>Many handlers<br>        ↓<br>One session CoroutineScope<br>        ↓<br>Two platform hosts</pre><p>Android hosts that session through its foreground-execution model. iOS hosts the same Kotlin session through the background capabilities available on iOS. Where a capability such as background location needs different delivery mechanics, the platform can use them without redefining the business session.</p><p>The operating systems remain different. Their background constraints remain different. The courier-session ownership model does not need to be.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-8-realtime-telemetry-session-behavior-not-screen-accidents-b9427aba1494">Part 8</a> moves inside the shared session and looks at the handlers themselves: realtime communication, geofencing, telemetry, and GPS backfill.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d85f64011c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-7-background-service-one-scope-many-handlers-two-hosts-a7d85f64011c">Part 7 — Background Service: One Scope, Many Handlers, Two Hosts</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 6 — Permissions: The Edge That Unlocks Every Other Edge]]></title>
            <link>https://medium.com/getir/part-6-permissions-the-edge-that-unlocks-every-other-edge-d554b281e4ef?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/d554b281e4ef</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:13:52 GMT</pubDate>
            <atom:updated>2026-11-16T11:10:54.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RIbjLpH5qlMLhO9ehd2ow.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 6 of 11</em></p><p><a href="https://medium.com/getir/part-5-hard-sdk-edges-maps-ml-kit-camera-sensors-and-coil-11b0c26cb7cf">Part 5</a> covered the device-facing SDK edges behind maps, barcode scanning, camera, sensors, location, geofencing, and image loading. None of those capabilities work reliably without the right authorization state.</p><p>Part 6 is about that permission layer:</p><ul><li>how Android and iOS declare permissions</li><li>how each platform actually requests them</li><li>which permissions cannot be treated as generic prompts</li><li>how permanent denial turns into a Settings flow</li><li>how a shared PermissionGate keeps courier startup honest</li></ul><p>This is not a Manifest appendix. Permissions are part of the product architecture.</p><h3>Why Permissions Deserve Their Own Part</h3><p>After the hard SDK edges, permissions are easy to treat as boilerplate. In a courier app, that is a mistake. Without the correct authorization state:</p><ul><li>live courier location cannot work reliably</li><li>background location cannot feed operational handlers</li><li>camera flows cannot verify packages</li><li>motion and activity signals cannot feed telemetry</li><li>notifications cannot support operational messaging paths</li></ul><p>So the real question is not only:</p><pre>Is CameraX wired?<br>Is CLLocationManager created?<br>Does Core Motion compile?</pre><p>It is also:</p><pre>Is this capability allowed right now?<br>Have we declared it correctly?<br>Are we allowed to ask the user yet?<br>Can we ask again?<br>Or is Settings now the only valid path?</pre><p>Android and iOS answer those questions differently. The shared application still needs one product-level answer.</p><h3>The Shared Contract</h3><p>We did not put Android Manifest permission names or iOS Info.plist keys into commonMain. Instead, shared code talks to capability-specific handlers. Conceptually:</p><pre>expect object ForegroundLocationPermissionHandler {<br>    fun isPermissionGranted(): Boolean<br>    fun isPermissionPermanentlyDenied(): Boolean<br>    suspend fun requestPermission(): PermissionResult<br>}</pre><p>Similar handlers exist for capabilities such as:</p><ul><li>background location</li><li>activity recognition</li><li>camera</li><li>notifications</li><li>phone-state access</li><li>Android-only operational concerns such as battery optimization and overlay behavior</li></ul><p>The shared result intentionally stays small:</p><pre>sealed class PermissionResult {<br>    object Granted : PermissionResult()<br>    data class Denied(val isPermanentlyDenied: Boolean) : PermissionResult()<br>}</pre><p>Shared screens and gates do not branch on:</p><pre>shouldShowRequestPermissionRationale(...)<br>CLAuthorizationStatus.authorizedWhenInUse<br>CLAuthorizationStatus.denied<br>UNAuthorizationStatus<br>Android API-level quirks</pre><p>They branch on the product outcome:</p><pre>Granted<br>Denied<br>Denied + permanently denied</pre><p>That is the abstraction we needed.</p><h3>PermissionGate: Ordered Reality, Not Wishful Parallelism</h3><p>Courier startup does not ask for every permission at once. A shared PermissionChecker or PermissionGateScreen walks an ordered sequence. Conceptually:</p><pre>0. platform / service sanity checks<br>1. foreground location<br>2. location services enabled<br>3. background location<br>4. battery optimization       [Android]<br>5. overlay / OEM path         [Android]<br>6. phone-state access         [Android]<br>7. activity recognition<br>8. notifications              [selected flows]</pre><p>The exact list can evolve. That order is product policy.</p><p>Asking for background location before foreground location is not just poor UX. Depending on platform and OS version, it can be ineffective or invalid. Likewise, on iOS, Always authorization should not be modeled as a completely separate first request detached from When In Use.</p><p>So the gate encodes an escalation strategy:</p><pre>reach a workable foreground state<br>        ↓<br>escalate where operationally necessary<br>        ↓<br>handle platform-only requirements<br>        ↓<br>continue with motion / activity<br>        ↓<br>keep feature-scoped permissions outside startup</pre><p>Not every permission needs to block cold start. That distinction matters.</p><h3>Camera Is a Feature Permission</h3><p>Camera is a clear example. It is mandatory for:</p><ul><li>barcode scanning</li><li>proof capture</li><li>other operational camera flows</li></ul><p>But that does not mean every courier session should request camera permission at splash. Instead, we request it when the feature actually needs it. That keeps startup narrower, and it keeps the permission explanation next to the action that triggered it.</p><h3>Notifications Can Follow a Different Path</h3><p>Notifications are another example. They matter operationally, but they do not necessarily belong in the exact same startup cadence as location authorization. They may be handled later in the session through a deliberate flow instead of participating in every startup sequence.</p><p>The broader principle is simple: one permission architecture does not mean one giant dialog sequence.</p><h3>Android and iOS Are Not Symmetrical</h3><p>At the product level, the capabilities look similar. At the platform level, they are not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kip5vc3VFSLa9QtbtWo3hg.png" /></figure><p>The shared gate can look consistent. The platform answers underneath it are intentionally different. Shared policy does not require fake platform symmetry.</p><h3>Declaration Is Part of the Runtime Contract</h3><p>Before any system dialog appears, both platforms require declaration.</p><h3>Android</h3><p>Relevant Manifest declarations can include:</p><pre>ACCESS_COARSE_LOCATION<br>ACCESS_FINE_LOCATION<br>ACCESS_BACKGROUND_LOCATION<br>FOREGROUND_SERVICE<br>FOREGROUND_SERVICE_LOCATION<br>CAMERA<br>POST_NOTIFICATIONS<br>ACTIVITY_RECOGNITION<br>REQUEST_IGNORE_BATTERY_OPTIMIZATIONS<br>SYSTEM_ALERT_WINDOW<br>READ_PHONE_STATE</pre><h3>iOS</h3><p>Relevant Info.plist purpose descriptions can include:</p><pre>NSLocationWhenInUseUsageDescription<br>NSLocationAlwaysAndWhenInUseUsageDescription<br>NSMotionUsageDescription<br>NSCameraUsageDescription</pre><p>plus background modes where required.</p><p>That difference matters because the failure modes are different. On Android, missing declarations often show up as denied capability or runtime failure paths. On iOS, missing required purpose descriptions for protected APIs can cause much sharper failures.</p><p>So declaration is not documentation. It is executable platform configuration. Permissions begin before requestPermission() is ever called.</p><h3>How Requests Actually Happen</h3><p>The shared API may look uniform:</p><pre>requestPermission()</pre><p>The platform mechanics are not.</p><h3>Android Request Flow</h3><p>Conceptually:</p><pre>Manifest declaration<br>        ↓<br>optional product explanation<br>        ↓<br>Activity Result launcher<br>        ↓<br>system dialog<br>        ↓<br>Granted<br>or<br>Denied<br>        ↓<br>rationale / retry / permanent-deny handling<br>        ↓<br>Settings when needed</pre><p>Permission launchers need a host lifecycle. For example, handlers may be wired early from the host Activity:</p><pre>ForegroundLocationPermissionHandler.setActivityResultListener()<br>BackgroundLocationPermissionHandler.setActivityResultListener()<br>ActivityRecognitionPermissionHandler.setActivityResultListener()<br>NotificationPermissionHandler.setActivityResultListener()<br>CameraPermissionHandler.setActivityResultListener()</pre><p>Without that binding, a suspend-style shared API has no Android result channel underneath it. A shared API does not remove platform ownership. It only hides it from callers.</p><h3>iOS Request Flow</h3><p>iOS has no universal equivalent of the Android Activity Result permission launcher. Each framework owns its own authorization flow. Conceptually:</p><pre>Info.plist declaration<br>        ↓<br>authorization state<br>        ↓<br>framework-specific request<br>        ↓<br>Authorized<br>Denied<br>Restricted<br>        ↓<br>Settings when no further prompt is possible</pre><p>Examples include:</p><pre>CLLocationManager.requestWhenInUseAuthorization()<br>CLLocationManager.requestAlwaysAuthorization()<br>AVCaptureDevice.requestAccess(...)<br>UNUserNotificationCenter.requestAuthorization(...)<br>Core Motion API usage</pre><p>The shared API is one shape. The underlying mechanisms are several.</p><h3>Location: Foreground First, Background Second</h3><p>Location is the clearest case of ordered permission policy.</p><h3>Android</h3><p>Foreground comes first:</p><pre>ACCESS_FINE_LOCATION<br>or<br>ACCESS_COARSE_LOCATION</pre><p>Then, where required and supported:</p><pre>ACCESS_BACKGROUND_LOCATION</pre><p>Our shared flow does not treat background permission as independent. If foreground access is missing, escalation is not complete.</p><h3>iOS</h3><p>The conceptual progression is similar, but the APIs are different:</p><pre>requestWhenInUseAuthorization()<br>        ↓<br>authorizedWhenInUse<br>        ↓<br>requestAlwaysAuthorization()<br>        ↓<br>authorizedAlways</pre><p>When In Use and Always are different operational states. For a courier workload that needs background location behavior, When In Use is not the same thing as completion. The shared policy therefore becomes:</p><pre>foreground location granted<br>        ↓<br>background escalation attempted<br>        ↓<br>required background state reached<br>        ↓<br>background-dependent handlers can proceed</pre><p>commonMain consumes PermissionResult. It does not duplicate the full CLAuthorizationStatus state machine across screens.</p><h3>Activity Recognition: When the Capability Triggers the Permission</h3><p>This is one of the biggest Android/iOS differences in the permission layer.</p><h3>Android</h3><p>Activity recognition behaves like a standard runtime permission on relevant Android versions:</p><pre>ACTIVITY_RECOGNITION</pre><p>It can be requested through the Android permission flow. Once granted, Play Services activity-recognition APIs can operate.</p><h3>iOS</h3><p>There is no identical standalone generic motion-permission request API. The system authorization flow is tied more closely to the capability itself. The application declares:</p><pre>NSMotionUsageDescription</pre><p>Then platform code interacts with Core Motion, for example through CMMotionActivityManager. Conceptually:</p><pre>CMMotionActivityManager<br>        ↓<br>start activity updates / query<br>        ↓<br>system authorization behavior<br>        ↓<br>observe authorization state</pre><p>That creates an important rule: some iOS permissions are entered through the capability itself, not through a generic permission launcher. If the application never touches the relevant Core Motion API, there may be no prompt to show.</p><p>Shared code can still say:</p><pre>ActivityRecognitionPermissionHandler.requestPermission()</pre><p>but the iOS implementation may need to initiate real Core Motion interaction underneath that call. That is what the platform edge is for.</p><h3>Camera: Keep the Ask Close to the Feature</h3><h3>Android</h3><pre>CAMERA<br>→ Activity Result permission flow</pre><h3>iOS</h3><pre>NSCameraUsageDescription<br>+<br>AVCaptureDevice authorization</pre><p>Shared barcode and photo screens request camera when the user enters the feature.</p><h3>Notifications: Same Product Need, Different Platform Model</h3><p>Notifications support operational messaging. The permission model differs.</p><h3>Android</h3><p>On newer Android versions:</p><pre>POST_NOTIFICATIONS</pre><p>Older platform versions behave differently because notification permission was historically not exposed as the same runtime request.</p><h3>iOS</h3><pre>UNUserNotificationCenter.requestAuthorization(...)</pre><h3>Android-Only Operational Permissions Are Still Real Architecture</h3><p>Some operational Android problems simply do not exist in the same form on iOS. Examples can include:</p><ul><li>battery optimization exemptions</li><li>overlay permission on selected flows</li><li>Play Services availability</li><li>location-settings resolution</li><li>OEM-specific background behavior</li></ul><p>iOS does not need fake equivalents for those concerns. On iOS, the corresponding shared handlers can legitimately return success or behave as no-ops where the concept does not exist. That asymmetry is correct. The wrong abstraction would be:</p><pre>Android has Xiaomi background settings<br>        ↓<br>therefore commonMain invents<br>&quot;iOS Xiaomi background settings&quot;</pre><p>That is not portability. That is fiction. The better model is:</p><pre>Shared gate step<br>        ↓<br>Android actual performs work<br>iOS actual passes through where irrelevant</pre><p>Common code owns the product sequence. The platform decides whether the step requires real mechanics.</p><h3>Permanent Denial Changes the Flow</h3><p>Eventually, both platforms reach states where asking again is not useful. The signals differ.</p><h3>Android</h3><p>Permanent denial is inferred from runtime behavior such as:</p><ul><li>repeated denial</li><li>rationale state</li><li>a “don’t ask again”-style outcome</li><li>platform / API-specific behavior</li></ul><h3>iOS</h3><p>Denied or Restricted often means the app cannot simply display the same authorization prompt again. The flow becomes a Settings flow. Shared UX can therefore look like:</p><pre>product explanation<br>        ↓<br>request permission<br>        ↓<br>denied<br>        ↓<br>retry where valid<br>        ↓<br>permanently denied<br>        ↓<br>open Settings<br>        ↓<br>app resumes<br>        ↓<br>recheck gate</pre><h3>Android Settings</h3><p>Common destinations include app-details Settings:</p><pre>ACTION_APPLICATION_DETAILS_SETTINGS</pre><p>with specialized intents for battery or overlay cases where needed.</p><h3>iOS Settings</h3><p>The general app Settings route uses:</p><pre>UIApplicationOpenSettingsURLString</pre><p>And this exposes another platform reality: you often cannot deep-link the user directly to the exact iOS permission toggle you want. Sometimes “open the app’s Settings page” is the whole supported control surface. Shared UX has to respect that limit instead of inventing precision the OS does not give us.</p><h3>What Common Code Owns — and What It Refuses</h3><p>The boundary is easier to follow when ownership is explicit.</p><h3>commonMain owns</h3><ul><li>permission-handler contracts</li><li>PermissionResult</li><li>ordered permission policy</li><li>PermissionGateScreen</li><li>ask-versus-Settings decisions</li><li>which permissions block startup</li><li>which permissions stay feature-scoped</li></ul><h3>androidMain owns</h3><ul><li>Manifest declarations</li><li>Activity Result launchers</li><li>rationale behavior</li><li>battery / overlay Settings intents</li><li>Play Services resolution</li><li>OEM-specific operational behavior</li></ul><h3>iosMain owns</h3><ul><li>Info.plist purpose descriptions</li><li>Core Location authorization</li><li>AVFoundation camera authorization</li><li>UserNotifications authorization</li><li>Core Motion authorization behavior</li></ul><h3>commonMain refuses</h3><ul><li>Manifest permission strings scattered through screens</li><li>CLAuthorizationStatus switches inside ViewModels</li><li>assumptions that every Android permission has an iOS twin</li><li>assumptions that every iOS capability has a generic standalone permission request</li></ul><p>That refusal keeps the shared layer on product policy instead of OS trivia. Do not make common code pretend the operating systems share one permission model. Let common code own the product sequence. Let each platform perform the legal request underneath it.</p><h3>Dual Maintenance Still Exists at the Permission Edge</h3><p>Shared handlers reduce product drift. They do not remove platform verification.</p><p>If background-location policy changes, both Android and iOS escalation need retesting. If activity recognition moves earlier in startup, the Android gate order changes, and iOS still needs to trigger the Core Motion authorization path correctly. If camera becomes startup-scoped, both platform handlers and the shared gate order change. If an OEM battery path breaks, only Android changes.</p><p>And that is fine. The migration did not eliminate platform maintenance. It moved that maintenance behind PermissionResult. That is the right boundary.</p><h3>What Permissions Changed for Us</h3><p>Hard SDK edges make a courier multiplatform app possible. Permissions are what make those edges usable at runtime.</p><p>Android gets there through:</p><pre>Manifest<br>+<br>runtime permission APIs<br>+<br>Activity-bound launchers<br>+<br>Settings / OEM flows</pre><p>iOS gets there through:</p><pre>Info.plist purpose descriptions<br>+<br>framework authorization APIs<br>+<br>capability-triggered prompts<br>+<br>Settings</pre><p>Those systems are not identical. They do not need to be. The shared layer only has to reduce them to the product decision:</p><pre>Granted<br>Denied<br>Settings</pre><p>That is the boundary that mattered.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-7-background-service-one-scope-many-handlers-two-hosts-a7d85f64011c">Part 7</a> moves to what happens after authorization is granted: how operational work stays alive when the UI is gone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d554b281e4ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-6-permissions-the-edge-that-unlocks-every-other-edge-d554b281e4ef">Part 6 — Permissions: The Edge That Unlocks Every Other Edge</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 5 — Hard SDK Edges: Maps, ML Kit, Camera, Sensors, and Coil]]></title>
            <link>https://medium.com/getir/part-5-hard-sdk-edges-maps-ml-kit-camera-sensors-and-coil-11b0c26cb7cf?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/11b0c26cb7cf</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:13:44 GMT</pubDate>
            <atom:updated>2026-11-16T11:10:19.473Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><p><em>Getir MDU × Compose Multiplatform Migration, Part 5 of 11</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6-zlEwsKozoTvTq1BgINw.png" /></figure><p>Parts 1 through <a href="https://medium.com/getir/part-4-shared-navigation-from-activities-and-fragments-to-one-graph-cec871866c2d?postPublishedType=repub">part 4</a> covered migration order, infrastructure, shared presenters, and shared navigation. Part 5 moves into the device-facing side of that work.</p><p>A courier app leans hard on capabilities that are platform-specific by nature: maps, camera, barcode scanning, location, sensors, geofencing, and image decoding. Compose Multiplatform can share the screens and product behavior around those capabilities. It cannot make the underlying SDKs identical.</p><p>What we landed on was simple:</p><ul><li>keep product policy in commonMain</li><li>keep native SDK mechanics inside platform implementations</li><li>normalize platform output before shared business logic consumes it</li><li>treat lifecycle, threading, and callback ownership as part of the platform boundary</li></ul><p>The rest of this part walks through those boundaries one by one.</p><h3>Device Capabilities Are Part of the Product</h3><p>For MDU, device integrations are not side features. Couriers depend on:</p><ul><li>live maps</li><li>courier and warehouse markers</li><li>external turn-by-turn navigation</li><li>barcode and QR verification</li><li>camera capture for operational proof</li><li>GPS streams</li><li>accelerometer and gyroscope telemetry</li><li>geofencing</li><li>image and GIF loading inside shared Compose screens</li></ul><p>A failure in any of them can stop a delivery flow. That pushed us to rethink what multiplatform architecture meant here.</p><p>The goal was not to hide every native SDK behind an abstraction just to push more code into shared modules. What mattered was whether Android and iOS could expose the same product-level behavior while still using their native SDKs correctly underneath.</p><h3>The Boundary Pattern</h3><p>Most device-facing integrations follow the same general structure:</p><pre>commonMain<br>├── product-facing API<br>├── shared models<br>└── orchestration around the capability<br>androidMain<br>├── Android / Google SDKs<br>└── Android lifecycle and threading<br>iosMain<br>├── Apple frameworks<br>├── Swift Package Manager SDKs<br>└── UIKit / AVFoundation / CoreLocation wiring</pre><p>Shared screens call the common API. They do not need to import:</p><pre>Google Maps Compose<br>CameraX<br>ML Kit Android clients<br>AVFoundation<br>CoreLocation<br>GMSMapView</pre><p>The shared layer deals with product concepts such as:</p><pre>Location<br>DetectedBarcode<br>CapturedPhoto<br>SensorEvent<br>MapPadding</pre><p>rather than vendor SDK types. The SDK remains at the edge of the architecture.</p><h3>Threading Is Part of the Platform Contract</h3><p>expect/actual is often treated as a type-level abstraction. For device integrations, that only gets you halfway. The platform implementation also has to decide where callbacks run, and which thread or queue is allowed to touch native UI or shared state.</p><p>Android and iOS are not symmetrical here. An integration can be correct at the API level and still fail because a callback lands on the wrong thread. For us, thread ownership became part of the platform contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcwAjGlK3Ufl1QGIhl08cw.png" /></figure><h3>Google Maps: One MapComponent, Two Implementations</h3><p>The Home experience needs a real map. Shared code does not need to know whether that map is backed by Maps Compose or GMSMapView. It only needs to define what the product expects from the map.</p><h3>commonMain</h3><pre>@Composable<br>expect fun MapComponent(<br>    modifier: Modifier = Modifier,<br>    courierLocation: Pair&lt;Double, Double&gt;? = null,<br>    warehouseLocations: List&lt;Pair&lt;Double, Double&gt;&gt; = emptyList(),<br>    focusTrigger: Int = 0,<br>    padding: MapPadding = MapPadding(),<br>    onCameraCenterChanged: ((Double, Double) -&gt; Unit)? = null,<br>)</pre><p>The shared API owns product-level inputs such as:</p><ul><li>courier coordinates</li><li>warehouse coordinates</li><li>focus requests</li><li>map padding</li><li>optional camera-center callbacks</li></ul><p>It does not expose:</p><pre>GoogleMap<br>GMSMapView<br>LatLng<br>BitmapDescriptorFactory<br>GMSMarker</pre><h3>Android actual</h3><p>Android uses Maps Compose and Play Services Maps. A simplified implementation looks like this:</p><pre>@Composable<br>actual fun MapComponent(...) {<br>    val cameraPositionState = rememberCameraPositionState {<br>        position = CameraPosition.fromLatLngZoom(initialLocation, 15f)<br>    }<br>    GoogleMap(<br>        cameraPositionState = cameraPositionState,<br>        properties = MapProperties(mapType = MapType.NORMAL),<br>        uiSettings = MapUiSettings(zoomControlsEnabled = false),<br>        onMapLoaded = {<br>            // Marker factories are ready here.<br>        },<br>    ) {<br>        courierLatLng?.let {<br>            Marker(state = MarkerState(it), icon = courierIcon)<br>        }<br>        warehouseLatLngs.forEach {<br>            Marker(state = MarkerState(it), icon = warehouseIcon)<br>        }<br>    }<br>}</pre><p>The main Android dependencies are:</p><pre>com.google.maps.android:maps-compose<br>com.google.android.gms:play-services-maps</pre><h3>iOS actual</h3><p>On iOS, we use Google Maps through Swift Package Manager and host GMSMapView inside Compose with UIKitView.</p><pre>@Composable<br>actual fun MapComponent(...) {<br>    UIKitView(<br>        factory = {<br>            GMSMapView().apply {<br>                // Markers<br>                // Camera<br>                // Padding<br>                // Styling<br>            }<br>        },<br>        update = { mapView -&gt;<br>            // Apply courier location.<br>            // Apply warehouse updates.<br>            // React to focusTrigger.<br>        },<br>        modifier = modifier,<br>    )<br>}</pre><p>The implementation depends on:</p><pre>GoogleMaps Swift package<br>UIKitView<br>GMSMapView<br>GMSMarker<br>GMSCameraUpdate</pre><p>The map contract is shared. The view lifecycle is not. GMSMapView is UIKit, so map mutations and camera operations remain Main-aware. If a location stream arrives from a background coroutine, we cross back to Main before touching the native view.</p><h3>Shared Policy Above the Map SDK</h3><p>The two map implementations are very different internally. The product behavior does not need to be. The way Android or iOS moves the actual map camera remains a platform detail.</p><h3>External Navigation Is Another Platform Edge</h3><p>Displaying the map is one problem. Opening turn-by-turn navigation is another. The shared contract can remain simple:</p><pre>expect class MapNavigationManager() {<br>    suspend fun openDirections(<br>        destinationLat: Double,<br>        destinationLng: Double,<br>        currentLat: Double,<br>        currentLng: Double,<br>        navigationPreference: Int,<br>    ): Result&lt;Unit&gt;<br>}</pre><p>Android can resolve this through an Intent or URI. Depending on configuration, that may open Google Maps or Yandex. iOS can use URL schemes for Google Maps, Apple Maps, or Yandex.</p><p>The shared screen only asks to open directions to a destination. It does not need to know which native application handles the request.</p><h3>Barcode Scanning: One Output Model, Two Camera Pipelines</h3><p>Barcode verification is part of courier operations. The shared layer owns concepts such as:</p><ul><li>BarcodeScannerView</li><li>DetectedBarcode</li><li>BarcodeFormat</li><li>OnBarcodesDetected</li><li>confirmation and rejection logic</li></ul><p>The platform implementation owns camera frames and ML Kit integration.</p><h3>Android: CameraX + ML Kit</h3><p>The Android pipeline looks roughly like this:</p><pre>CameraX Preview<br>      ↓<br>ImageAnalysis<br>      ↓<br>Dedicated Executor<br>      ↓<br>ML Kit BarcodeScanning<br>      ↓<br>DetectedBarcode<br>      ↓<br>Main<br>      ↓<br>Compose / ViewModel</pre><p>A simplified analyzer:</p><pre>private val analysisExecutor = Executors.newSingleThreadExecutor()<br>private val mainHandler = Handler(Looper.getMainLooper())<br>imageAnalysis.setAnalyzer(<br>    analysisExecutor,<br>    BarcodeCodeAnalyzer { barcodes, size -&gt;<br>        val detected = barcodes.map { it.toDetectedBarcode() }<br>        mainHandler.post {<br>            onBarcodesDetected(detected, size.width, size.height)<br>        }<br>    },<br>)</pre><p>Then:</p><pre>cameraProvider.bindToLifecycle(lifecycleOwner, selector, preview, imageAnalysis)</pre><p>The split is intentional:</p><pre>frame analysis<br>    → background<br>Compose / ViewModel update<br>    → Main</pre><p>STRATEGY_KEEP_ONLY_LATEST is especially useful here. Camera frames can arrive faster than ML Kit can process them. Building a queue of stale frames usually makes scanning worse rather than better. For interactive barcode scanning, the latest frame is normally more useful than catching up on old ones.</p><h3>iOS: AVFoundation + ML Kit</h3><p>The iOS pipeline is different:</p><pre>AVCaptureSession<br>      ↓<br>AVCaptureVideoDataOutput<br>      ↓<br>capture queue<br>      ↓<br>ML Kit BarcodeScanning<br>      ↓<br>DetectedBarcode<br>      ↓<br>Main queue<br>      ↓<br>Compose / ViewModel</pre><p>Conceptually:</p><pre>dispatch_async(dispatch_get_main_queue()) {<br>    session.startRunning()<br>    onReady()<br>}</pre><p>We start the session on the next run loop so the UIKitView is already in the hierarchy. That avoids a first-open issue where frames were not delivered until the screen was reopened.</p><p>Frame callbacks arrive through the video output:</p><pre>override fun captureOutput(...) {<br>    val image = MLKVisionImage(buffer = sampleBuffer)<br>    barcodeScanner.processImage(image) { barcodes, error -&gt;<br>        val detected = barcodes.map { it.toDetectedBarcode() }<br>        dispatch_async(dispatch_get_main_queue()) {<br>            onBarcodesDetected(detected, width, height)<br>        }<br>    }<br>}</pre><p>The camera pipeline is platform-specific. The shared output is not:</p><pre>Android<br>CameraX + ML Kit<br>        ↓<br>DetectedBarcode<br><br>iOS<br>AVFoundation + ML Kit<br>        ↓<br>DetectedBarcode</pre><p>Once the platform has produced DetectedBarcode, the rest of the flow can remain shared.</p><h3>Camera Capture</h3><p>Photo capture follows the same pattern. The shared layer can own:</p><ul><li>flashEnabled</li><li>captureTrigger</li><li>CapturedPhoto</li><li>success callbacks</li><li>error callbacks</li></ul><p>The native platform owns the camera stack itself.</p><h3>Android</h3><p>Android uses:</p><pre>CameraX Preview<br>ImageCapture<br>ProcessCameraProvider<br>LifecycleOwner<br>CameraControl</pre><p>Thread ownership still matters. Lifecycle binding is Main-aware. File operations, compression, and other expensive processing can move to IO or Default. Any state consumed by Compose returns to Main.</p><h3>iOS</h3><p>The equivalent implementation uses:</p><pre>AVCaptureSession<br>AVCaptureVideoPreviewLayer<br>AVFoundation photo capture<br>AVCaptureDevice torch<br>UIKitView</pre><p>Calling the APIs is usually the easy part. Getting the session, native preview, Compose host, and lifecycle to line up is harder. UIKit-backed preview mutations are Main-sensitive. Capture completion can happen elsewhere and needs to cross back before updating shared UI state.</p><p>Bugs around this boundary often show up as intermittent first-open failures or preview initialization problems when session setup races with view attachment. Those bugs are easy to miss in small sample apps and much easier to hit under real timing.</p><h3>Location: The Contract Is Shared, Acquisition Is Not</h3><p>Location is one of the clearest cases where the two platform implementations should stay different. The shared API can still be the same:</p><pre>interface LocationManager {<br>    val locationState: StateFlow&lt;LocationState&gt;<br>    val lastSuccessfulLocation: StateFlow&lt;Location?&gt;<br>    val locationChannel: SharedFlow&lt;Pair&lt;Long, Location&gt;&gt;<br>    fun startLocationUpdates()<br>    fun stopLocationUpdates()<br>}</pre><p>GPilot, our session telemetry pipeline, geofencing, and other shared consumers work with these streams. They do not need to see:</p><pre>FusedLocationProviderClient<br>android.location.Location<br>CLLocationManager<br>CLLocation</pre><h3>Android: Fused Location + HandlerThread</h3><p>Continuous location on Android roughly follows:</p><pre>location-services check<br>    ↓<br>LocationRequest<br>    ↓<br>HandlerThread(&quot;LocationUpdates&quot;)<br>    ↓<br>FusedLocationProviderClient<br>    ↓<br>LocationCallback<br>    ↓<br>shared Location<br>    ↓<br>StateFlow / SharedFlow</pre><p>Conceptually:</p><pre>val thread = HandlerThread(&quot;LocationUpdates&quot;).apply {<br>    isDaemon = true<br>    start()<br>}<br>try {<br>    fusedClient.requestLocationUpdates(locationRequest, callback, thread.looper)<br>} catch (_: Exception) {<br>    // Handle failure.<br>}</pre><p>Cleanup matters:</p><pre>awaitClose {<br>    fusedClient.removeLocationUpdates(callback)<br>    thread.quitSafely()<br>}</pre><p>A dedicated callback thread is useful because location delivery can be noisy. There is no reason every GPS callback has to arrive on Main before shared code has even decided whether it is useful.</p><p>For one-shot location, the same idea applies:</p><pre>suspend fun getCurrentLocation(...): LocationResult =<br>    withContext(dispatcherProvider.io) {<br>        // Check location services.<br>        // Await current location.<br>        // Map to shared result.<br>    }</pre><h3>iOS: CLLocationManager</h3><p>The iOS implementation follows a different lifecycle model:</p><pre>configure CLLocationManager<br>    ↓<br>authorization state<br>    ↓<br>assign delegate<br>    ↓<br>startUpdatingLocation()<br>    ↓<br>didUpdateLocations<br>    ↓<br>shared Location<br>    ↓<br>StateFlow / SharedFlow</pre><p>Conceptually:</p><pre>private val locationManager = CLLocationManager()<br>private val scope = CoroutineScope(SupervisorJob() + dispatcherProvider.main)<br><br>locationManager.desiredAccuracy = kCLLocationAccuracyBest<br>locationManager.delegate = delegate<br>locationManager.startUpdatingLocation()</pre><p>Location callbacks are normalized immediately:</p><pre>override fun locationManager(<br>    manager: CLLocationManager,<br>    didUpdateLocations: List&lt;*&gt;,<br>) {<br>    val clLocation = didUpdateLocations.lastOrNull() as? CLLocation ?: return<br>    val shared = clLocation.toSharedLocation()<br>    _lastSuccessfulLocation.value = shared<br>    _locationChannel.tryEmit(currentTimeMillis() to shared)<br>}</pre><p>This is deliberately different from Android. Android can deliver fused-location callbacks on a background looper. CLLocationManager has different run-loop and delegate ownership expectations. On iOS, we keep manager creation, delegate ownership, start/stop calls, and one-shot location work Main-aware. Heavy work can move elsewhere after the callback has been normalized into the shared Location model.</p><p>The common layer does not need both operating systems to acquire location the same way. It needs them to produce the same product-level representation.</p><h3>Geofencing: Software and Native Paths</h3><p>We did not force geofencing into one implementation. We kept two paths:</p><pre>1. Software geofencing in shared code<br>2. Native OS geofencing behind PlatformGeofenceManager</pre><p>They solve different problems.</p><h3>Software Geofencing</h3><p>Active task-geofence evaluation can run from the shared location stream. Conceptually:</p><pre>LocationManager<br>      ↓<br>shared Location<br>      ↓<br>GeofenceTriggerProcessor<br>      ↓<br>distance + accuracy evaluation<br>      ↓<br>ENTER / EXIT / DWELL</pre><p>A collector can look like:</p><pre>scope.launch(dispatchers.io) {<br>    locationManager.lastSuccessfulLocation.collect { location -&gt;<br>        if (location != null) {<br>            triggerProcessor.checkAllGeofences(location) {<br>                // Product-level confirmation logic<br>            }<br>        }<br>    }<br>}</pre><p>The reason to keep this path in shared code is product behavior. Some geofence requirements go beyond what the native region APIs offer cleanly:</p><ul><li>custom DWELL behavior</li><li>overlapping or onion geofences</li><li>accuracy-aware enter/exit calculations</li><li>product-level race resolution</li></ul><p>Those decisions should behave the same on both platforms. If we implemented that logic independently using Android and iOS geofence APIs, identical courier movement could produce different outcomes.</p><h3>Native OS Geofencing</h3><p>Native geofencing is still useful when we want the operating system to monitor regions. That lives behind another shared contract:</p><pre>// commonMain<br>interface PlatformGeofenceManager {<br>    val platformEvents: SharedFlow&lt;PlatformGeofenceEvent&gt;<br>    fun addGeofences(<br>        geofences: List&lt;GeofenceServiceDomainModel&gt;,<br>    ): Flow&lt;GeofenceRegistrationResult&gt;<br>    fun removeGeofences(geofenceIds: List&lt;String&gt;): Flow&lt;GeofenceRemovalResult&gt;<br>    fun removeAllGeofences(): Flow&lt;GeofenceRemovalResult&gt;<br>    fun isAvailable(): Boolean<br>}</pre><p>Factory:</p><pre>expect fun createPlatformGeofenceManager(): PlatformGeofenceManager</pre><p>Shared consumers still see one API.</p><h3>Android Native Geofencing</h3><p>Android uses:</p><pre>GeofencingClient<br>Geofence.Builder<br>GeofencingRequest<br>PendingIntent<br>BroadcastReceiver</pre><p>Conceptually:</p><pre>val platformGeofences = geofences.map { model -&gt;<br>    Geofence.Builder()<br>        .setRequestId(model.id)<br>        .setCircularRegion(model.latitude, model.longitude, model.radius)<br>        .setTransitionTypes(model.toAndroidTransitionTypes())<br>        .setLoiteringDelay(model.dwellDelay.toInt())<br>        .setExpirationDuration(Geofence.NEVER_EXPIRE)<br>        .build()<br>}</pre><p>Then:</p><pre>val request = GeofencingRequest.Builder()<br>    .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)<br>    .addGeofences(platformGeofences)<br>    .build()<br><br>geofencingClient.addGeofences(request, pendingIntent)</pre><p>The BroadcastReceiver maps Android transition events back into PlatformGeofenceEvent.</p><h3>iOS Native Geofencing</h3><p>iOS uses:</p><pre>CLLocationManager<br>CLCircularRegion<br>startMonitoringForRegion()<br>stopMonitoringForRegion()<br>CLLocationManagerDelegate</pre><p>Conceptually:</p><pre>geofences.forEach { model -&gt;<br>    val region = CLCircularRegion(<br>        center = CLLocationCoordinate2DMake(model.latitude, model.longitude),<br>        radius = model.radius.toDouble(),<br>        identifier = model.id,<br>    )<br>    locationManager.startMonitoringForRegion(region)<br>}</pre><p>Delegate events are mapped into the common model:</p><pre>PlatformGeofenceEvent(<br>    id = region.identifier,<br>    transition = ENTER,<br>)</pre><p>The two paths remain separate:</p><pre>Software geofencing<br>    consumes LocationManager<br>    owns product math in common code<br><br><br>Native geofencing<br>    consumes PlatformGeofenceManager<br>    owns OS region registration</pre><p>Both are useful. Neither requires Play Services or Core Location types to leak into shared business code.</p><h3>Sensors: Producing Comparable Samples on Two Platforms</h3><p>GPilot needs accelerometer and gyroscope data. The shared interface is the easy part. What matters more is how Android and iOS produce values that can safely enter the same telemetry pipeline.</p><h3>Android: SensorManager + HandlerThread</h3><p>Android starts with SensorManager:</p><pre>val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager<br><br>val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)<br>val gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)</pre><p>Sensor delivery can stay off Main:</p><pre>val thread = HandlerThread(&quot;Accelerometer-Thread&quot;).apply {<br>    isDaemon = true<br>    start()<br>}</pre><p>Then:</p><pre>val listener = object : SensorEventListener {<br>    override fun onSensorChanged(event: android.hardware.SensorEvent?) {<br>        val values = event?.values ?: return<br>        val mapped = SensorEvent(<br>            x = values[0],<br>            y = values[1],<br>            z = values[2],<br>            timestamp = currentTimeMillis(),<br>        )<br>        sharedFlow.tryEmit(mapped)<br>    }<br>    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit<br>}</pre><p>Registration:</p><pre>sensorManager.registerListener(<br>    listener,<br>    accelerometer,<br>    SENSOR_SAMPLING_MICROS,<br>    Handler(thread.looper),<br>)</pre><p>Cleanup:</p><pre>sensorManager.unregisterListener(listener)<br>thread.quitSafely()</pre><p>Sensor callbacks can arrive very frequently. Sampling and throttling therefore belong close to the platform source. By the time samples reach shared telemetry, common code should only need to understand SensorEvent.</p><h3>iOS: CMMotionManager + NSOperationQueue</h3><p>The iOS implementation uses Core Motion:</p><pre>val motionManager = CMMotionManager()<br>val operationQueue = NSOperationQueue()<br><br>motionManager.accelerometerUpdateInterval = 0.1<br>motionManager.gyroUpdateInterval = 0.1</pre><p>Accelerometer delivery:</p><pre>motionManager.startAccelerometerUpdatesToQueue(operationQueue) { data, error -&gt;<br>    if (error != null || data == null) {<br>        return@startAccelerometerUpdatesToQueue<br>    }<br>    val event = SensorEvent(<br>        x = (-data.acceleration.x * STANDARD_GRAVITY).toFloat(),<br>        y = (-data.acceleration.y * STANDARD_GRAVITY).toFloat(),<br>        z = (-data.acceleration.z * STANDARD_GRAVITY).toFloat(),<br>        timestamp = currentTimeMillis(),<br>    )<br>    sharedFlow.tryEmit(event)<br>}</pre><p>Gyroscope delivery follows the same callback structure, but not the same physical conversion:</p><pre>motionManager.startGyroUpdatesToQueue(operationQueue) { data, error -&gt;<br>    if (error != null || data == null) {<br>        return@startGyroUpdatesToQueue<br>    }<br>    val event = SensorEvent(<br>        x = data.rotationRate.x.toFloat(),<br>        y = data.rotationRate.y.toFloat(),<br>        z = data.rotationRate.z.toFloat(),<br>        timestamp = currentTimeMillis(),<br>    )<br>    sharedFlow.tryEmit(event)<br>}</pre><p>Cleanup remains important:</p><pre>motionManager.stopAccelerometerUpdates()<br>motionManager.stopGyroUpdates()</pre><h3>Sensor Normalization Belongs at the Edge</h3><p>Android accelerometer data is reported in m/s². Core Motion accelerometer values are reported in G, and 1 G is roughly 9.81 m/s². So the same physical movement can arrive with different magnitudes across platforms.</p><p>Before an iOS accelerometer sample enters the shared model, we normalize the unit:</p><pre>data.acceleration.x * STANDARD_GRAVITY</pre><p>We also normalize axis direction according to the convention expected by our telemetry pipeline:</p><pre>-data.acceleration.x * STANDARD_GRAVITY</pre><p>The negative sign is specific to our shared coordinate convention. It is not a general rule that every iOS axis should always be inverted relative to Android.</p><p>Shared telemetry needs a consistent physical representation. Without this normalization, the same movement could enter shared code with different units, magnitudes, and axis signs. That would push platform-specific sensor semantics into the telemetry layer.</p><p>Gyroscope data is different. Rotation rate is already angular velocity, so accelerometer conversion rules such as STANDARD_GRAVITY must not be applied to it. The callback pattern may look similar. The physics are not.</p><h3>Coil 3: One Image API in Shared Screens</h3><p>Images are another area where it is easy to accidentally create separate platform stacks. We wanted shared Compose screens to use the same image-loading direction across features such as:</p><ul><li>gamification</li><li>feedback</li><li>product cards</li><li>chatbot</li><li>remote content</li></ul><p>The shared contract is small:</p><pre>expect fun getImageLoader(): ImageLoader</pre><p>Shared screens use:</p><pre>AsyncImage(<br>    model = imageUrl,<br>    imageLoader = getImageLoader(),<br>    contentDescription = &quot;foo&quot;,<br>)</pre><h3>Android</h3><pre>private val imageLoaderSingleton by lazy {<br>    val context = AppContext.get().applicationContext<br>    ImageLoader.Builder(context)<br>        .memoryCache {<br>            MemoryCache.Builder()<br>                .maxSizePercent(context, MEMORY_CACHE_MAX_SIZE_PERCENT)<br>                .build()<br>        }<br>        .components { add(AnimatedImageDecoder.Factory()) }<br>        .build()<br>}<br><br>actual fun getImageLoader(): ImageLoader = imageLoaderSingleton</pre><h3>iOS</h3><pre>private val imageLoaderSingleton by lazy {<br>    ImageLoader.Builder(PlatformContext.INSTANCE)<br>        .build()<br>}<br><br>actual fun getImageLoader(): ImageLoader = imageLoaderSingleton</pre><p>Where GIF support is required, it follows the same image-loading direction instead of introducing another custom stack per platform. The screen-level API remains shared. Decoder configuration, caching, and platform setup stay inside the platform layer.</p><h3>Comparison Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HygJRe4Z9cCqzXjj6BNBOA.png" /></figure><p>The product-facing abstractions are shared. The underlying SDK mechanics are deliberately not.</p><h3>What We Chose Not to Share</h3><p>A solid KMP architecture is not just about maximizing commonMain. Some platform behavior belongs on the platform.</p><p>We did not build a fake portable implementation of Google Maps. We use Google Maps on both platforms behind one product-facing API.</p><p>We did not replace ML Kit with a weaker cross-platform scanner just to avoid native code. We use ML Kit on both sides and normalize its result into DetectedBarcode.</p><p>We did not expose CameraX or AVFoundation classes to common code. Shared code sees concepts such as CapturedPhoto and controller commands.</p><p>We did not let GPilot depend on Android sensor types. The platform layer emits normalized SensorEvent values instead.</p><p>That keeps commonMain focused on product meaning rather than vendor SDK details. The shared layer should not need to understand how CameraX, Core Motion, GMSMapView, or CLLocationManager behave internally. The native side should translate those mechanics into a product-level contract first.</p><h3>Dual Maintenance Still Exists at the Platform Edge</h3><p>Shared abstractions reduce business-logic duplication. They do not eliminate platform QA.</p><p>If barcode behavior changes, both pipelines still need verification. If map focus rules change, Android and iOS need to honor the same shared inputs. If camera behavior changes, both native implementations still need testing. If image loading changes, both loaders must continue supporting the same shared AsyncImage call sites.</p><p>That duplication is expected. It exists where the operating systems are genuinely different. What we wanted to avoid was repeating product policy above those boundaries.</p><h3>What Hard SDK Edges Changed for Us</h3><p>Maps, barcode scanning, camera, sensors, location, geofencing, and media loading are all part of the product surface. Compose Multiplatform let us share the product behavior around them without pretending the platforms underneath were the same. The resulting structure looked roughly like this:</p><pre>Android mechanics<br>        ↓<br>shared product contract<br>        ↑<br>iOS mechanics</pre><p>Android can use CameraX, Play Services, Maps Compose, SensorManager, and fused location. iOS can use AVFoundation, Google Maps through Swift Package Manager, Core Motion, and Core Location.</p><p>Shared Kotlin does not need to choose between those implementations. It defines what the rest of the product expects from them.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-6-permissions-the-edge-that-unlocks-every-other-edge-d554b281e4ef">Part 6</a> covers the permission layer around these device integrations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b0c26cb7cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-5-hard-sdk-edges-maps-ml-kit-camera-sensors-and-coil-11b0c26cb7cf">Part 5 — Hard SDK Edges: Maps, ML Kit, Camera, Sensors, and Coil</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4 — Shared Navigation: From Activities and Fragments to One Graph]]></title>
            <link>https://medium.com/getir/part-4-shared-navigation-from-activities-and-fragments-to-one-graph-cec871866c2d?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/cec871866c2d</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:13:35 GMT</pubDate>
            <atom:updated>2026-11-16T11:10:00.134Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZCoaVKDc2DJviwr2IqKqw.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 4 of 11</em></p><p><a href="https://medium.com/getir/part-3-one-presenter-contract-for-two-platforms-2ff8c81057d6?postPublishedType=repub">Part 3</a> introduced the presenter contract we use across migrated features: UIAction in, UIState and UIEvent out. That gave Android and iOS the same way to talk to presentation logic.</p><p>Navigation was the next problem. A presenter can emit:</p><pre>NavigateToHome<br>NavigateToDelivery<br>NavigateToScan</pre><p>but something still has to define what those destinations mean, what arguments they carry, how the back stack behaves, and how each platform hosts them. We moved that responsibility into shared code gradually:</p><ul><li>a sealed route model</li><li>a shared NavHost</li><li>a clear boundary between UIEvent and navigation execution</li><li>a hybrid Android host during coexistence</li><li>explicit bridges for legacy Activities and Fragments</li></ul><p>We did not replace the Android navigation stack in one step. For a significant period, the shared graph and the existing Android graph ran together.</p><h3>What Navigation Looked Like Before CMP</h3><p>The legacy Android application did not have one navigation graph. Navigation was spread across Activities, Fragments, Intent-based transitions, bottom navigation, local Fragment stacks, and nested Fragment hosts. At a high level, there were three common navigation paths:</p><pre>Activity<br>   │<br>   ├── Intent ─────────────→ Activity<br>   │<br>   └── FragmentManager<br>            │<br>            ├── ADD<br>            └── REPLACE<br>                    ↓<br>                 Fragment</pre><p>In practice:</p><ol><li>Activity → Activity through Intent</li><li>Activity → Fragment through FragmentManager</li><li>Fragment → Fragment through FragmentTransaction</li></ol><p>There was nothing unusual about that for a mature Android application. The hard part showed up when Android and iOS needed to consume the same product flow. Navigation behavior was encoded through Android-specific concepts such as:</p><ul><li>Activity classes</li><li>Intent extras</li><li>Intent flags</li><li>FragmentManager</li><li>FragmentTransaction</li><li>container IDs</li><li>bottom-navigation IDs</li><li>helper methods such as callingIntent(...)</li></ul><p>So even after business logic moved to shared Kotlin, a large part of product navigation still lived in Android implementation details.</p><h3>Activity-to-Activity Navigation</h3><p>Cross-feature movement often happened through Intents. Different courier types could also resolve to different Activity classes. A simplified Home resolver looked like this:</p><pre>class HomeActivityNavigator(<br>    private val typeLocalDataSource: CourierTypeLocalDataSource,<br>) {<br>    fun callingIntent(context: Context): Intent {<br>        return when (courierType) {<br>            CourierType.COURIER -&gt; Intent(context, HomeActivity::class.java)<br>            CourierType.DRIVER -&gt; Intent(context, TmsHomeActivity::class.java)<br>            CourierType.RESTAURANT -&gt; Intent(context, RduHomeActivity::class.java)<br>            else -&gt; Intent(context, SplashActivity::class.java)<br>        }.apply {<br>            flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK<br>        }<br>    }<br>}</pre><p>Navigation then became:</p><pre>startActivity(homeActivityNavigator.callingIntent(this))</pre><p>The Intent was doing more than naming the next screen. The selected Activity class, extras, task flags, and current Activity stack all contributed to navigation behavior. A product concept like Home was still partly represented by Android classes and task semantics.</p><h3>Navigation Inside an Activity</h3><p>Opening an Activity did not necessarily mean the navigation flow ended there. An Activity could host another local navigation structure. A Home-style Activity could look conceptually like this:</p><pre>HomeActivity<br>│<br>├── SupportMapFragment<br>│<br>├── BottomNavigation / pager<br>│   ├── Home<br>│   ├── Profile<br>│   ├── Notifications<br>│   └── Gamification<br>│<br>└── Overlay Fragments / Bottom Sheets</pre><p>A map Fragment could be retrieved through:</p><pre>val mapFragment =<br>    supportFragmentManager.findFragmentById(R.id.homeMapView) as SupportMapFragment</pre><pre>mapFragment.getMapAsync(this)</pre><p>Bottom navigation could use the same supportFragmentManager through a pager or adapter. So one Activity might be responsible for:</p><ul><li>lifecycle</li><li>system chrome</li><li>map integration</li><li>tab navigation</li><li>overlays</li><li>navigation into other Activities</li></ul><p>That worked on Android. It also meant product navigation was tied tightly to Android lifecycle and Fragment infrastructure.</p><h3>Containers and Back Stacks Were Part of the Flow</h3><p>Fragment navigation introduced another level of complexity. A Fragment is placed into a container owned by an Activity or another Fragment. Conceptually:</p><pre>Activity layout<br>│<br>├── Toolbar / chrome<br>│<br>├── FragmentContainerView<br>│       ↑<br>│       Fragment destination<br>│<br>└── BottomNavigation</pre><p>A normal transition could look like this:</p><pre>transaction.replace(R.id.featureContainer, NextFragment())<br>transaction.addToBackStack(null)<br>transaction.commit()</pre><p>or:</p><pre>transaction.add(R.id.featureContainer, OverlayFragment())<br>transaction.addToBackStack(&quot;overlay&quot;)<br>transaction.commit()</pre><p>These look like implementation details. They directly affect product behavior. The resulting flow depends on:</p><ul><li>which Activity owns the container</li><li>which container receives the Fragment</li><li>whether the transaction uses ADD or REPLACE</li><li>whether it enters the back stack</li><li>whether parentFragmentManager or childFragmentManager owns that stack</li></ul><p>For example:</p><pre>parentFragmentManager<br>    → stack owned by the parent host</pre><pre>childFragmentManager<br>    → nested stack owned by the Fragment</pre><p>A flow could therefore contain several active stacks:</p><pre>Android task / Activity stack<br>    └── HomeActivity<br>            └── supportFragmentManager<br>                    └── TaskHostFragment<br>                            └── childFragmentManager<br>                                    └── Form<br>                                        → Wait<br>                                        → Confirmation</pre><p>Back behavior then depended on which stack currently owned the visible destination. A simplified Activity implementation might be:</p><pre>override fun onBackPressed() {<br>    val fragmentManager = supportFragmentManager<br>    if (fragmentManager.backStackEntryCount &gt; 0) {<br>        fragmentManager.popBackStack()<br>    } else {<br>        super.onBackPressed()<br>    }<br>}</pre><p>A nested host might have its own rule:</p><pre>if (childFragmentManager.backStackEntryCount &gt; 0) {<br>    childFragmentManager.popBackStack()<br>} else {<br>    // Bubble upward<br>}</pre><p>ADD and REPLACE also meant different things. REPLACE was useful for step-to-step navigation. ADD was useful when the previous content needed to remain underneath, such as layered or modal flows. Both could participate in the back stack.</p><p>So a feature’s back behavior could depend on the Activity stack, Fragment stack, nested Fragment stack, transaction strategy, and Intent flags all at once.</p><p>Useful on Android. Also very specific to Android.</p><h3>Fragment-to-Fragment Navigation</h3><p>Some features went another level deeper. We had helper abstractions around Fragment transactions:</p><pre>class FragmentNavigator(<br>    private val currentFragment: Fragment,<br>) {<br>    fun navigateWithParentFragmentManager(<br>        strategy: FragmentTransactionStrategy = FragmentTransactionStrategy.REPLACE,<br>        @IdRes containerId: Int,<br>        fragment: () -&gt; Fragment,<br>    ) {<br>        val transaction = currentFragment.parentFragmentManager.beginTransaction()<br>        when (strategy) {<br>            FragmentTransactionStrategy.ADD -&gt; {<br>                transaction.add(containerId, fragment())<br>                transaction.addToBackStack(null)<br>            }<br>            FragmentTransactionStrategy.REPLACE -&gt; {<br>                transaction.replace(containerId, fragment())<br>                transaction.addToBackStack(null)<br>            }<br>        }<br>        transaction.commit()<br>    }</pre><pre>    fun navigateWithChildFragmentManager(<br>        // ...<br>    ) {<br>        // Same idea using childFragmentManager<br>    }<br>}</pre><p>Subtask-style flows were especially Fragment-heavy. They could include screens such as:</p><pre>FormTaskComponentFragment<br>WaitTaskComponentFragment<br>InfoTaskComponentFragment<br>ConfirmationTaskComponentFragment</pre><p>hosted by one or more container Activities. A courier journey could therefore cross several navigation systems:</p><pre>LoginActivity<br>      ↓ Intent<br>HomeActivity<br>      ↓ Intent<br>TaskHostActivity<br>      ↓ REPLACE<br>FormTaskComponentFragment<br>      ↓ ADD / REPLACE<br>ConfirmationTaskComponentFragment<br>      ↓ popBackStack / finish()<br>HomeActivity</pre><p>That was workable on Android. Not a graph we wanted to rebuild separately on iOS.</p><h3>Moving Navigation Into Shared Code</h3><p>By this point in the migration, the presenter layer was already shared. If navigation stayed completely platform-specific after that, the architecture would split again immediately:</p><pre>Shared Presenter<br>       │<br>    UIEvent<br>   ┌───┴───┐<br>   ↓       ↓<br>Android   iOS<br>Router    Router</pre><p>Both platforms would independently interpret product flow. Over time, route arguments, deeplinks, Home resolution, back behavior, and feature entry points would drift.</p><p>So destination identity moved into shared code. The platform still hosts navigation. It does not get to define the product graph on its own.</p><h3>Moving Routes Into commonMain</h3><p>The shared route hierarchy is sealed, serializable, and type-safe. A simplified version looks like this:</p><pre>@Serializable<br>sealed class Route {<br>    abstract val route: String<br>    @Serializable<br>    sealed class AuthGraph : Route() {<br>        @Serializable<br>        data object Splash : AuthGraph() {<br>            override val route = &quot;splash&quot;<br>        }<br>        @Serializable<br>        data class Login(val source: String? = null) : AuthGraph() {<br>            override val route = &quot;login&quot;<br>        }<br>    }<br>    @Serializable<br>    sealed class MainGraph : Route() {<br>        @Serializable<br>        data class Home(val tab: String? = null) : MainGraph() {<br>            override val route = &quot;home&quot;<br>        }<br>        @Serializable<br>        data class TmsHome(val ref: String? = null) : MainGraph() {<br>            override val route = &quot;tmsHome&quot;<br>        }<br>        @Serializable<br>        data class Delivery(val taskId: String) : MainGraph() {<br>            override val route = &quot;delivery&quot;<br>        }<br>    }<br>}</pre><p>The product graph can now be represented directly:</p><pre>Route<br>│<br>├── AuthGraph<br>│   ├── Splash<br>│   ├── Login<br>│   ├── ForgotPassword<br>│   ├── EnterCode<br>│   └── ...<br>│<br>└── MainGraph<br>    ├── Home<br>    ├── TmsHome<br>    ├── Go<br>    ├── Delivery<br>    ├── Notify<br>    ├── Gamification<br>    ├── Profile / Settings<br>    ├── GForce<br>    └── ...</pre><p>Before this migration, the same destination might be represented by:</p><pre>HomeActivity<br>TmsHomeActivity<br>RduHomeActivity<br>DeliveryActivity<br>Intent extras<br>Fragment arguments<br>container IDs<br>addToBackStack()<br>popBackStack()</pre><p>Now shared code can use:</p><pre>Route.MainGraph.Home(...)<br>Route.MainGraph.TmsHome(...)<br>Route.MainGraph.Delivery(...)</pre><p>One detail matters here. A shared Route existing did not mean that destination was already a CMP screen. During coexistence, a route could still resolve to an Android Activity or Fragment. That distinction mattered throughout the migration.</p><h3>The Shared NavHost</h3><p>Migrated screens are registered inside the shared navigation shell. For example:</p><pre>NavHost(<br>    navController = navController,<br>    startDestination = Route.AuthGraph.Splash,<br>) {<br>    composable&lt;Route.AuthGraph.Login&gt; { entry -&gt;<br>        val args = entry.toRoute&lt;Route.AuthGraph.Login&gt;()<br>        LoginScreen(<br>            onEvent = { event -&gt; handleLoginEvent(navController, event) }<br>        )<br>    }<br>    composable&lt;Route.MainGraph.Delivery&gt; { entry -&gt;<br>        val args = entry.toRoute&lt;Route.MainGraph.Delivery&gt;()<br>        DeliveryScreen(taskId = args.taskId)<br>    }<br>}</pre><p>Android still needs an Activity to host this. That part did not disappear. What changed was what the Activity was responsible for.</p><p>Previously, an Activity might own destination identity, Intent handling, local Fragment graphs, containers, back-stack behavior, and lifecycle. The target architecture was closer to:</p><pre>SharedContainerActivity<br>        ↓<br>platform host<br>        ↓<br>shared application shell<br>        ↓<br>NavHost<br>        ↓<br>Route</pre><p>The Activity becomes a host for the shared graph, not the graph itself. iOS can host the same route model without reproducing Android’s Activity and Fragment architecture.</p><p>We did not reach that end state immediately.</p><h3>SharedContainerActivity Was a Hybrid Host</h3><p>This was one of the most useful parts of the migration. The shared NavHost did not replace every Android destination at once. For a significant period, SharedContainerActivity hosted both architectures:</p><pre>SharedContainerActivity<br>│<br>├── App() / shared NavHost<br>│       migrated CMP destinations<br>│<br>└── FragmentContainerView overlay<br>        unmigrated Fragment destinations</pre><p>Conceptually:</p><pre>setContent {<br>    App(<br>        navigationManager = navigationManager,<br>        startDestination = getStartDestination(),<br>        onActivityNavigation = { route -&gt; handleActivityNavigation(route) },<br>        onFragmentNavigation = { route -&gt; handleNativeFragmentNavigation(route) },<br>    )<br>    if (showFragmentContainer) {<br>        AndroidView(<br>            factory = { fragmentContainer },<br>            update = { view -&gt;<br>                view.visibility = if (showFragmentContainer) View.VISIBLE else View.GONE<br>            }<br>        )<br>    }<br>}</pre><p>Migrated destinations stayed inside the shared NavHost. Legacy Fragment destinations could still be shown through the FragmentContainerView.</p><p>From the outside it looked like one Android Activity. Internally it was bridging two navigation systems. That let us migrate destination by destination instead of waiting on full parity.</p><h3>Legacy Fragments Could Live on Top of CMP</h3><p>Some Home tabs, such as Notifications or Gamification, could remain as Fragments even after the surrounding shell had moved to CMP. A simplified bridge looked like this:</p><pre>private fun handleNativeFragmentNavigation(route: Route?) {<br>    when (route) {<br>        is Route.MainGraph.Notifications -&gt; {<br>            navigateToFragment(MessageListFragment.getInstance(), &quot;notifications&quot;)<br>        }<br>        is Route.MainGraph.Gamification -&gt; {<br>            navigateToFragment(GamificationHomeFragment.getInstance(), &quot;gamification&quot;)<br>        }<br>        is Route.MainGraph.Home,<br>        is Route.MainGraph.Profile -&gt; {<br>            closeFragmentContainer()<br>        }<br>        else -&gt; Unit<br>    }<br>}</pre><p>And:</p><pre>private fun navigateToFragment(fragment: Fragment, tag: String) {<br>    showFragmentContainer = true<br>    backPressedCallback.isEnabled = true<br>    supportFragmentManager<br>        .beginTransaction()<br>        .replace(fragmentContainerId, fragment, tag)<br>        .commitAllowingStateLoss()<br>}</pre><p>The CMP bottom navigation could remain visible while the legacy Fragment occupied the main content area. Back handling belonged to that overlay first:</p><pre>private val backPressedCallback = object : OnBackPressedCallback(false) {<br>    override fun handleOnBackPressed() {<br>        if (showFragmentContainer &amp;&amp; supportFragmentManager.backStackEntryCount &gt; 0) {<br>            supportFragmentManager.popBackStackImmediate()<br>            if (supportFragmentManager.backStackEntryCount == 0) {<br>                showFragmentContainer = false<br>                isEnabled = false<br>            }<br>        }<br>    }<br>}</pre><p>Once the overlay was gone, navigation control returned to the CMP graph. Expected Android behavior stayed intact while the destination was still being migrated.</p><h3>Legacy Activities Stayed as Explicit Bridges</h3><p>Not every legacy destination made sense as a Fragment overlay. A number of flows still lived in full Activities for a while, such as:</p><ul><li>Delivery</li><li>Go</li><li>Notify</li><li>GForce</li><li>Order History</li><li>Edit Profile</li><li>Forgot Password</li><li>other still-native flows</li></ul><p>Those used an Activity bridge:</p><pre>private fun handleActivityNavigation(route: Route?) {<br>    when (route) {<br>        null -&gt; finish()<br>        is Route.MainGraph.Home -&gt; startActivity(homeActivityNavigator.callingIntent(this))<br>        is Route.MainGraph.Go -&gt; startActivity(GoTaskActivity.callingIntent(this))<br>        is Route.MainGraph.Delivery -&gt; startActivity(DeliveryTaskActivity.callingIntent(this))<br>        is Route.MainGraph.Notify -&gt; startActivity(NotifyTaskActivity.callingIntent(this))<br>        is Route.MainGraph.GForce -&gt; startActivity(GForceMainActivity.callingIntent(this))<br>        else -&gt; Unit<br>    }<br>}</pre><p>So during coexistence, a shared route could result in three different execution paths:</p><pre>Route<br>  ↓<br>  ├── shared NavHost<br>  ├── legacy Fragment overlay<br>  └── legacy Activity bridge</pre><p>That was deliberate. The route model could move into shared code before every destination implementation moved with it.</p><h3>What Actually Changed</h3><p>This migration was not simply:</p><pre>Fragments<br>    ↓<br>Compose Navigation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ_1-M4QQS9BUQ1eg7LiXg.png" /></figure><p>Several responsibilities moved at different times. Typed arguments could move into the route model even before every screen had moved to CMP. The same applied to deeplink metadata. Navigation identity could move earlier than destination implementation.</p><h3>Where UIEvent Becomes Navigation</h3><p>Part 3 intentionally stopped at UIEvent. A presenter might emit:</p><pre>NavigateToSplash<br>NavigateToForgotPassword<br>OpenPrivacyPolicy<br>ForceRestart<br>ShowToast</pre><p>It does not execute those operations itself. In the old Android implementation, an event could eventually become:</p><pre>startActivity(...)<br>fragmentNavigator.replace(...)<br>addToBackStack(...)<br>popBackStack()<br>finish()<br>open bottom sheet</pre><p>In the shared application shell, that interpretation happens outside the presenter. For example:</p><pre>fun handleLoginEvent(navController: NavHostController, event: LoginUIEvent) {<br>    when (event) {<br>        LoginUIEvent.NavigateToSplash -&gt; {<br>            navController.navigate(Route.AuthGraph.Splash) { popUpTo(0) }<br>        }<br>        is LoginUIEvent.NavigateToForgotPassword -&gt; {<br>            navController.navigate(Route.AuthGraph.ForgotPassword(resetType = event.resetType))<br>        }<br>        is LoginUIEvent.OpenPrivacyPolicy -&gt; urlOpener.open(event.url)<br>        is LoginUIEvent.ShowToast -&gt; showToast(event.message)<br>        LoginUIEvent.ForceRestart -&gt; platformRestarter.restart()<br>    }<br>}</pre><p>The presenter does not know about NavController, Intents, Fragment containers, or how iOS hosts the route. It only emits the outcome. The application shell decides how that outcome is executed.</p><h3>Home Resolution Was Still Hybrid for a While</h3><p>Home is a useful example because route ownership and destination migration did not happen at the same time. In the legacy application:</p><pre>when (courierType) {<br>    COURIER -&gt; HomeActivity<br>    DRIVER -&gt; TmsHomeActivity<br>    RESTAURANT -&gt; RduHomeActivity<br>}</pre><p>During coexistence, the shared graph could already emit:</p><pre>Route.MainGraph.Home</pre><p>while SharedContainerActivity still called:</p><pre>homeActivityNavigator.callingIntent(this)</pre><p>That means the shared route said Home, but Android could still resolve that route to HomeActivity, TmsHomeActivity, or RduHomeActivity depending on courier type.</p><p>We did not treat route migration and screen migration as the same milestone. The route identity could move first. The Android hosting implementation could remain legacy for longer. Later, destinations such as Route.MainGraph.Home and Route.MainGraph.TmsHome could become actual CMP screens.</p><p>That gradual transition is a more accurate description than pretending every Home variant moved together.</p><h3>Navigation Was Migrated Destination by Destination</h3><p>For a while, the application deliberately contained both systems. The rule was:</p><ul><li>migrated destinations use the shared NavHost</li><li>unmigrated Fragment destinations use the SharedContainerActivity overlay</li><li>unmigrated Activity destinations use explicit Activity bridges</li><li>partially migrated flows keep those bridges visible</li></ul><p>Conceptually:</p><pre>Legacy graph                 Shared graph<br><br>Activity A ───────┐<br>Fragment B ───────┼── migration boundary<br>Activity C ───────┘<br>                          ↓<br>                       Route A<br>                       Route B<br>                       Route C<br>                          ↓<br>                  ┌───────┼────────┐<br>                  ↓       ↓        ↓<br>               NavHost  Fragment  Activity<br>                        overlay   bridge</pre><p>Destinations crossed one at a time. The intermediate state was less elegant than the final architecture. It was much easier to operate safely.</p><h3>Android First, Then iOS</h3><p>A destination becoming shared did not automatically mean we enabled it on both platforms right away. The rollout remained staged. A typical path looked like:</p><ol><li>Move the destination to CMP.</li><li>Run it on Android.</li><li>Exercise it under production courier traffic.</li><li>Treat it as mature after enough real usage.</li><li>Expose it on iOS once the core journey was ready.</li><li>Continue opening more shared destinations over time.</li></ol><p>Android already had production volume, so it stayed the proving ground. That let us validate routes, presenters, back behavior, and platform boundaries before exposing the same destination on iOS.</p><p>It also avoided temporary native iOS implementations that would later be replaced by CMP. We did not want this:</p><pre>Legacy Android<br>+<br>temporary Swift<br>+<br>future CMP</pre><p>The path was closer to:</p><pre>Legacy Android<br>      ↓<br>migrate<br>      ↓<br>CMP on Android<br>      ↓<br>production validation<br>      ↓<br>mature shared destination<br>      ↓<br>iOS</pre><h3>Keeping Incomplete Navigation Visible</h3><p>We kept unfinished migration work visible through markers such as:</p><pre>KMPPHASE-*</pre><p>Those markers covered areas such as:</p><ul><li>deferred routes</li><li>live-support wiring</li><li>inventory work</li><li>finance follow-ups</li><li>crash-logging migration</li></ul><p>The exact naming mattered less than the visibility. At any point, we wanted to be able to answer:</p><pre>Is this destination shared?<br>Is it intentionally still legacy?<br>Does it use the Fragment overlay?<br>Does it use an Activity bridge?<br>Can the old path be deleted?</pre><p>Much easier than rediscovering application flow by tracing Activities, Intent flags, FragmentTransactions, and nested FragmentManagers.</p><h3>Dual Maintenance Also Applied to Navigation</h3><p>For a while, both navigation systems remained active. That meant differences could appear in areas such as:</p><ul><li>deeplinks</li><li>back-stack behavior</li><li>Intent flags versus popUpTo</li><li>Fragment overlay behavior</li><li>route arguments</li><li>QA coverage</li><li>product changes touching both shared and legacy paths</li></ul><p>We used the same rule as for screens in Part 3. A new destination preferred a shared route, a CMP screen, and typed arguments, and we avoided adding new behavior only to the legacy path.</p><p>Temporary overlap was expected. Permanent duplicate routing was not.</p><h3>What Shared Navigation Gave Us</h3><p>The biggest change was not replacing Fragments with Compose Navigation. It was moving destination ownership out of Android-specific infrastructure.</p><p>During coexistence, application flow looked more like:</p><pre>Route<br>typed arguments<br>shared destinations where ready<br>Fragment overlays where needed<br>Activity bridges where needed<br>shared deeplink metadata<br>shared graph policy</pre><p>As destinations completed migration, the temporary bridges could disappear. Android and iOS still host navigation according to their own platform lifecycle. But they no longer need independent definitions of the product graph.</p><p>What we wanted to avoid was sharing presentation logic while letting Android and iOS independently define the product graph. That would just move the duplication to another layer.</p><h3>What Shared Navigation Changed</h3><p>Part 3 gave Android and iOS the same presenter contract. Shared Navigation extended that model to movement between features.</p><p>During the messy middle of the migration, SharedContainerActivity made that possible without forcing everything to cross at once. That let shared code start from a simple route decision:</p><pre>Which Route should this flow move to?</pre><p>The Android host could then decide whether that route currently meant a shared composable, a legacy Fragment overlay, or a legacy Activity.</p><p>As migration progressed, those temporary interpretations disappeared and routes increasingly mapped directly to shared destinations. That was the useful part: route ownership could move before every legacy screen was gone.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-5-hard-sdk-edges-maps-ml-kit-camera-sensors-and-coil-11b0c26cb7cf">Part 5</a> moves away from navigation and into the areas that remain closely tied to native platform SDKs. Once screens, presenters, and navigation are shared, most of what remains sits at the platform boundary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec871866c2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-4-shared-navigation-from-activities-and-fragments-to-one-graph-cec871866c2d">Part 4 — Shared Navigation: From Activities and Fragments to One Graph</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3 — One Presenter Contract for Two Platforms]]></title>
            <link>https://medium.com/getir/part-3-one-presenter-contract-for-two-platforms-2ff8c81057d6?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/2ff8c81057d6</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:13:25 GMT</pubDate>
            <atom:updated>2026-11-16T11:09:41.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hk2q84SreIM-EDoJpQ4D2A.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 3 of 11</em></p><p><a href="https://medium.com/getir/part-2-strangler-fig-replacing-the-engine-while-the-app-is-running-b86390df8e6a?postPublishedType=repub">Part 2</a> covered the infrastructure migration and how old and new stacks coexisted in production. Once that foundation was stable, the next problem was the presenter layer.</p><p>Sharing Compose screens only works if Android and iOS also agree on how those screens talk to application logic. For us that meant the same MVI-shaped contract on every migrated feature:</p><ul><li>UIAction for input</li><li>UIState for rendering</li><li>UIEvent for transient effects</li></ul><p>MVI-shaped rather than MVI: we kept the three-part screen contract, not a reducer-based model. State transitions live in the ViewModel. Both platforms get one predictable way to talk to the same presentation and business logic.</p><p>Navigation is Part 4.</p><h3>Why We Standardized the Presenter Layer</h3><p>A mature Android app picks up several presentation patterns over time. That may include:</p><ul><li>callback listeners</li><li>Fragment results</li><li>shared ViewModel shortcuts</li><li>navigation flags inside state</li><li>direct calls from screens to use cases</li><li>screen-specific event handling</li></ul><p>That can stay manageable when everything lives on one platform. It gets harder once Android and iOS consume the same presenter layer.</p><p>If both platforms render the same state and run the same business flow, the presenter cannot depend on Android-specific callback chains or Fragment behavior. We needed a small contract that stayed the same no matter which platform rendered the screen. The shape became:</p><pre>UIAction<br>    ↓<br>ViewModel<br>    ↓<br>UIState<br>UIEvent</pre><p>Every migrated feature follows that same boundary. The internals can be simple or messy depending on the feature. The screen-facing contract stays the same.</p><h3>The Presenter Contract</h3><p>The three parts are intentionally boring.</p><h3>UIAction</h3><p>UIAction represents input coming from the screen. For a login-style feature:</p><pre>sealed interface LoginUIAction {<br>    data class UsernameChanged(val username: String) : LoginUIAction<br>    data class PasswordChanged(val password: String) : LoginUIAction<br>    data object LoginClicked : LoginUIAction<br>    data class TabSelected(val index: Int) : LoginUIAction<br>    data object ForgotPasswordClicked : LoginUIAction<br>}</pre><p>The screen reports what happened. It does not pick which use case to run, or how the feature should react. That interpretation sits behind the presenter boundary. Same contract whether the input came from Android, iOS, or a shared Compose screen.</p><h3>UIState</h3><p>UIState represents the current rendering model. For example:</p><pre>data class LoginUIState(<br>    val username: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val selectedTabIndex: Int = 0,<br>    val isLoading: Boolean = false,<br>    val errorMessage: String? = null,<br>)</pre><p>This is the state the screen can observe and render again and again. It may contain things such as:</p><ul><li>current input values</li><li>selected tabs</li><li>loading state</li><li>visible error content</li><li>dialog state</li><li>screen-specific data</li></ul><p>What matters is that this state describes the current UI. It should stay safe to observe after recomposition or lifecycle changes.</p><h3>UIEvent</h3><p>Some results should not live in persistent rendering state. Navigation is a good example. So are toast messages, external URLs, restart requests, and similar one-time effects. Those leave through UIEvent. For example:</p><pre>sealed interface LoginUIEvent {<br>    data object NavigateToSplash : LoginUIEvent<br>    data class NavigateToForgotPassword(val resetType: Int) : LoginUIEvent<br>    data class OpenPrivacyPolicy(val url: String) : LoginUIEvent<br>    data object ForceRestart : LoginUIEvent<br>    data class ShowToast(val message: String) : LoginUIEvent<br>}</pre><p>That keeps one-shot behavior out of rendering state. Useful on login. Much more important on Delivery and Subtask.</p><h3>What a Migrated Feature Looks Like</h3><p>At a high level, a migrated feature follows this shape:</p><pre>Composable<br>├── observes UIState<br>├── sends UIAction<br>└── collects UIEvent<br>ViewModel<br>├── handles UIAction<br>├── updates UIState<br>├── emits UIEvent<br>└── calls domain use cases<br>Domain<br>└── has no dependency on Compose</pre><p>A simplified ViewModel might look like this:</p><pre>class LoginViewModel(<br>    private val loginUseCase: LoginUseCase,<br>) : ViewModel() {<br>    private val _uiState = MutableStateFlow(LoginUIState())<br>    val uiState: StateFlow&lt;LoginUIState&gt; = _uiState.asStateFlow()<br>    private val _eventFlow = MutableSharedFlow&lt;LoginUIEvent&gt;()<br>    val eventFlow = _eventFlow.asSharedFlow()<br>    private fun updateState(transform: (LoginUIState) -&gt; LoginUIState) {<br>        _uiState.update(transform)<br>    }<br>    fun onAction(action: LoginUIAction) {<br>        when (action) {<br>            is LoginUIAction.UsernameChanged -&gt;<br>                updateState { it.copy(username = action.username) }<br>            LoginUIAction.LoginClicked -&gt; sendLogin()<br>            LoginUIAction.ForgotPasswordClicked -&gt;<br>                viewModelScope.launch {<br>                    _eventFlow.emit(LoginUIEvent.NavigateToForgotPassword(getResetType().type))<br>                }<br>            // ...<br>        }<br>    }<br>}</pre><p>The screen then observes state, sends actions, and consumes events:</p><pre>@Composable<br>fun LoginScreen(<br>    onEvent: (LoginUIEvent) -&gt; Unit,<br>    viewModel: LoginViewModel = koinViewModel(),<br>) {<br>    val uiState by viewModel.uiState.collectAsState()<br>    LaunchedEffect(Unit) {<br>        viewModel.eventFlow.collect(onEvent)<br>    }<br>    LoginContent(state = uiState, onAction = viewModel::onAction)<br>}</pre><p>The ViewModel can use mutableStateOf, StateFlow, or another suitable state holder. That choice is an implementation detail. What we keep stable is the screen contract:</p><pre>UIAction → presenter<br>UIState → rendering<br>UIEvent → transient effects</pre><h3>Why One-Shot Events Matter on Courier Screens</h3><p>Login is a useful example because the contract is easy to see. Delivery and Subtask are closer to why we needed the separation. Those screens can coordinate flows such as:</p><ul><li>refreshing an active task</li><li>completing a delivery</li><li>entering confirmation codes</li><li>calling a customer</li><li>opening chat</li><li>barcode or scan flows</li><li>component lists</li><li>partial tasks</li><li>map actions</li><li>emergency entry points</li><li>inventory flows</li><li>popup dismissal</li><li>tab changes</li></ul><p>If all transient behavior is represented inside UIState, the model quickly starts accumulating fields such as:</p><pre>shouldNavigateToX<br>shouldShowToast<br>pendingUrlToOpen<br>oneTimeErrorMessage<br>shouldOpenDialog<br>shouldCloseScreen</pre><p>That causes problems because state is designed to be observed repeatedly. A boolean may survive longer than expected. A recomposition may see it again. A lifecycle change may expose it again. Once Android and iOS both consume the same presenter, each platform may invent its own rules for acknowledging and resetting those values.</p><p>So we keep transient outcomes outside the persistent state model. The presenter emits an event; the presentation layer handles it as an effect. That leaves UIState focused on what the screen currently shows.</p><h3>The Contract Did Not Mean Putting Everything in the ViewModel</h3><p>This distinction mattered more as more screens moved to the shared architecture. A consistent contract does not mean all feature logic lives in one class. Our ViewModels remain responsible for the presentation boundary: UIAction, UIState, and UIEvent. Larger coordination can sit behind that boundary:</p><pre>ViewModel<br>    ↓<br>UseCases<br>    ↓<br>Repositories / Services</pre><p>That keeps responsibilities narrower. The screen is responsible for rendering and forwarding actions. The ViewModel owns the presentation contract. The domain layer remains independent of Compose.</p><p>The contract stays consistent even when the implementation behind it gets more complex.</p><p>The contract should make the presentation layer easier to understand. It should not create a new monolith.</p><h3>Presenter Migration Also Required Dual Maintenance</h3><p>Part 2 described the temporary duplication at the infrastructure layer. The same thing happened at screen level. While a feature was only partially migrated:</p><ul><li>a product change could require updates in both legacy and CMP paths</li><li>QA sometimes had to validate both implementations</li><li>analytics behavior had to remain aligned</li><li>some bug fixes had to be applied twice</li></ul><p>We used a simple rule for where new work should go.</p><p><strong>New screen work:</strong> Prefer CMP and the shared presenter contract.</p><p><strong>Existing screen under significant change:</strong> If practical, use the change as an opportunity to complete the migration instead of extending the legacy implementation.</p><p><strong>Unmigrated screen:</strong> Keep the production legacy path until the shared replacement is ready.</p><p><strong>CMP replacement already active:</strong> Avoid adding new business branching only to the old implementation.</p><p>Temporary duplication was sometimes necessary for controlled rollout. What we did not want was permanent feature ownership in two separate implementations.</p><h3>What Standardizing the Presenter Layer Changed</h3><p>Once more features followed the same presenter contract, a few things got easier. Android and iOS could consume the same state model. Use cases stayed behind the presenter layer. Transient effects no longer needed to live inside persistent state. Larger courier flows could share their coordination logic across platforms.</p><p>It also gave new features a default structure. A feature generally started from:</p><pre>Screen<br>  ↓<br>UIAction<br>  ↓<br>ViewModel<br>  ↓<br>UseCases</pre><p>with:</p><pre>UIState ─────→ Screen<br>UIEvent ─────→ Effect</pre><p>That consistency matters more as the codebase grows. During the first few multiplatform screens, architecture is easy to keep under control because the migration itself is getting a lot of attention. The harder part comes later, when shared code is just normal product work.</p><p>Without a default structure, features start drifting. One may put navigation flags into state. Another may call use cases directly from a screen. Another may introduce callback chains. Another may keep adding responsibilities to a ViewModel until it becomes difficult to maintain.</p><p>The presenter contract gave us a common starting point, while still allowing feature-specific code behind it.</p><h3>What Changed for Us</h3><p>The infrastructure work from Part 2 made the shared stack production-ready. The presenter layer made that stack usable for shared product development. Android and iOS could interact with the same features through the same inputs, state, and effects.</p><p>At that point the shared Compose screen itself was relatively straightforward. It was just a consumer of the presenter contract.</p><p>What remained was navigation. The presenter could emit intentions such as:</p><pre>NavigateToDelivery<br>NavigateToScan<br>NavigateToHome</pre><p>But something still had to define what those destinations were, how arguments moved between them, and how the new shared navigation model could coexist with the existing Android Activity and Fragment structure.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-4-shared-navigation-from-activities-and-fragments-to-one-graph-cec871866c2d">Part 4</a> starts with the existing Android navigation model and how we gradually moved toward one shared route model across both platforms, without requiring every legacy destination to move at the same time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ff8c81057d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-3-one-presenter-contract-for-two-platforms-2ff8c81057d6">Part 3 — One Presenter Contract for Two Platforms</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 — Strangler Fig: Replacing the Engine While the App Is Running]]></title>
            <link>https://medium.com/getir/part-2-strangler-fig-replacing-the-engine-while-the-app-is-running-b86390df8e6a?source=rss----5138a1e0a250---4</link>
            <guid isPermaLink="false">https://medium.com/p/b86390df8e6a</guid>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Bünyamin Başoğlu]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:13:17 GMT</pubDate>
            <atom:updated>2026-11-16T11:09:23.044Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/1e0884c2b6ac">Erdem Uysal</a>, <a href="https://medium.com/u/3a7d27a3fe28">Bulut Serel</a>, <a href="https://medium.com/u/610b95860ed3">enesarisoy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NC6DQzf6Re2TMtVh4fiwWw.png" /></figure><p><em>Getir MDU × Compose Multiplatform Migration, Part 2 of 11</em></p><p>In <a href="https://medium.com/getir/part-1-why-this-app-why-cmp-and-why-order-matters-d100fd0bdac2?postPublishedType=repub">Part 1</a> we explained why migration order mattered so much for MDU. Part 2 is about what that looked like in practice.</p><p>We did not start by moving screens to Compose Multiplatform, and we did not start by building the iOS application. We started lower in the stack.</p><p>For roughly two months, parts of the KMP infrastructure ran inside the existing Android production application while the legacy architecture was still active. That period gave us a way to validate persistence, serialization, networking, and dependency injection under real courier traffic before adding CMP UI and iOS on top.</p><p>In many ways, this was the most important part of the migration.</p><h3>Applying the Strangler Fig Pattern Inside One Mobile App</h3><p>The Strangler Fig pattern is usually explained using backend systems. The basic idea is straightforward: introduce the new system next to the old one, gradually move traffic across, and remove the legacy path when it is no longer needed.</p><p>For MDU, the boundary was different. We were not replacing a collection of services. We were replacing parts of a live mobile application used by couriers every day. So for a while, both architectures had to exist inside the same APK. That meant combinations such as:</p><pre>Hilt                  + Koin<br>Retrofit              + Ktor<br>Gson                  + kotlinx.serialization<br>Android persistence   + Multiplatform persistence<br>Legacy screens        + CMP screens</pre><p>This coexistence was intentional. Features moved across one by one while the production application continued to ship. That created some temporary duplication and some uncomfortable boundaries, but it was still safer than attempting one complete rewrite and switching everything over at once.</p><h3>Why Infrastructure Came Before UI</h3><p>UI migrations are easier to see. If a screen is broken, there is usually an obvious symptom and a relatively clear rollback path.</p><p>Infrastructure failures are different. If authentication state, task recovery, local persistence, or serialization changes incorrectly during an application update, the resulting state can be much harder to understand. For example:</p><ul><li>the UI may think the courier is logged in while API calls fail authorization</li><li>task state may exist in one storage path but not another</li><li>state may behave correctly until process death</li><li>persisted JSON may no longer decode after an upgrade</li><li>a request may still compile while its wire format has changed</li></ul><p>Because of that, we treated persistence, serialization, networking, and DI as higher-risk migration surfaces than the UI toolkit itself.</p><p>Before asking whether Home could render with CMP, we wanted to know whether the shared infrastructure could survive actual Android production traffic without changing product behavior. That meant validating Room Multiplatform, DataStore, kotlinx.serialization, Ktor, and Koin first.</p><h3>The Android Production Canary</h3><p>Before the major CMP UI cutover and before putting significant production responsibility on iOS, we ran much of the shared infrastructure in the Android application for roughly two months.</p><p>New multiplatform libraries were introduced into the existing production app. Selected networking, persistence, and data flows started using them while large parts of the application still remained on the legacy stack.</p><p>During this period, we watched the same things we would watch after any risky production change:</p><ul><li>crashes</li><li>storage failures</li><li>authentication anomalies</li><li>request regressions</li><li>process recreation behavior</li><li>device and OEM differences</li></ul><p>The point was to separate variables. We did not want to discover a Ktor issue at the same time as an iOS lifecycle issue. We did not want to migrate Room, DataStore, serialization, DI, UI, and platform target in one release. And we did not want every feature to depend on the new stack before the infrastructure had been exercised enough.</p><p>By the time iOS started depending heavily on shared code, much of that shared engine had already been running in production. That removed a lot of uncertainty from the second half of the migration.</p><h3>Room → Room Multiplatform</h3><p>Room already participated in operational persistence and telemetry-related flows. Moving it to Room Multiplatform was therefore less about replacing an API and more about preserving behavior while moving database ownership into shared code.</p><p>The shared layer could own:</p><pre>Entities<br>DAOs<br>Database definition<br>Schema version<br>Shared database configuration</pre><p>Platform code could remain responsible for:</p><pre>Database file location<br>Platform-specific builder creation<br>Filesystem integration</pre><p>A simplified shared database definition looked like this:</p><pre>@Database(<br>    entities = [TelemetryChunkEntity::class, LocationInfoEntity::class],<br>    version = 1,<br>)<br>@ConstructedBy(TelemetryDatabaseConstructor::class)<br>abstract class TelemetryDatabase : RoomDatabase() {<br>    abstract fun dao(): TelemetryDao<br>    companion object {<br>        const val DB_NAME = &quot;telemetry.db&quot;<br>    }<br>}</pre><p>Room’s generated constructor is also declared in commonMain:</p><pre>@Suppress(&quot;NO_ACTUAL_FOR_EXPECT&quot;)<br>expect object TelemetryDatabaseConstructor : RoomDatabaseConstructor&lt;TelemetryDatabase&gt; {<br>    override fun initialize(): TelemetryDatabase<br>}</pre><p>The database schema, entities, DAOs, and database contract are now shared. What cannot be fully shared is the physical database location. Android and iOS follow different filesystem conventions, so we expose only the builder creation as a platform-specific boundary:</p><pre>expect fun getTelemetryDatabaseBuilder(): RoomDatabase.Builder&lt;TelemetryDatabase&gt;</pre><h3>Android</h3><p>On Android, we keep using the application’s standard database directory:</p><pre>actual fun getTelemetryDatabaseBuilder(): RoomDatabase.Builder&lt;TelemetryDatabase&gt; {<br>    val dbFile = AppContext.get().getDatabasePath(TelemetryDatabase.DB_NAME)<br>    return Room.databaseBuilder&lt;TelemetryDatabase&gt;(<br>        context = AppContext.get(),<br>        name = dbFile.absolutePath,<br>    )<br>}</pre><p>This also lets us preserve the existing database identity instead of silently creating a second database during migration.</p><h3>iOS</h3><p>On iOS, the database path is resolved through NSFileManager. We store it under the application&#39;s Application Support directory and make sure the directory exists before Room opens the database:</p><pre>@OptIn(ExperimentalForeignApi::class)<br>actual fun getTelemetryDatabaseBuilder(): RoomDatabase.Builder&lt;TelemetryDatabase&gt; {<br>    val fileManager = NSFileManager.defaultManager<br>    val appSupportUrl = fileManager.URLForDirectory(<br>        directory = NSApplicationSupportDirectory,<br>        inDomain = NSUserDomainMask,<br>        appropriateForURL = null,<br>        create = true,<br>        error = null,<br>    )!!<br>    fileManager.createDirectoryAtURL(<br>        url = appSupportUrl,<br>        withIntermediateDirectories = true,<br>        attributes = null,<br>        error = null,<br>    )<br>    val databaseUrl = appSupportUrl.URLByAppendingPathComponent(TelemetryDatabase.DB_NAME)<br>    return Room.databaseBuilder&lt;TelemetryDatabase&gt;(name = databaseUrl?.path!!)<br>}</pre><p>The rest of the database configuration can stay shared:</p><pre>getTelemetryDatabaseBuilder()<br>    .apply {<br>        if (!Platform.isAndroid) {<br>            setDriver(BundledSQLiteDriver())<br>        }<br>    }<br>    .setQueryCoroutineContext(Dispatchers.IO)<br>    .fallbackToDestructiveMigration(true)<br>    .build()</pre><p>This database holds telemetry data rather than task or session state, so a destructive fallback was an acceptable trade-off here.</p><p>This split gave us a useful ownership boundary. The shared layer owns the database model and configuration. The platform layer owns only the parts that genuinely depend on the operating system: where the database file lives and how the initial Room builder is created.</p><p>We also kept execution ownership explicit at repository level:</p><pre>suspend fun insertChunk(entity: TelemetryChunkEntity): Long =<br>    withContext(dispatchers.io) {<br>        database.dao().insertChunk(entity)<br>    }</pre><p>Room already supports coroutine-based execution, but keeping repository dispatching explicit made the execution model easier to reason about during the migration.</p><p>More importantly, the practical migration rules mattered more than the API shape:</p><ul><li>keep database identity stable during migration</li><li>avoid introducing two databases for the same operational dataset</li><li>keep the schema and DAO contract shared</li><li>test schema migrations independently from UI migration</li><li>stage persistence changes carefully</li><li>keep database execution ownership explicit</li><li>verify upgrade paths using real existing database files</li></ul><p>Database bugs are also exactly the kind of bugs that benefit from a production canary. They rarely appear in a clean demo flow. They tend to surface after application upgrades, process death, concurrent reads and writes, partially migrated installations, unusual storage conditions, or on devices whose lifecycle behavior we did not reproduce locally.</p><p>For that reason, database migration was treated as an operational change rather than simply another shared-code refactor. Moving Room into commonMain was valuable, but preserving the existing persistence behavior was more important than maximizing shared-code percentage.</p><h3>DataStore → Multiplatform DataStore</h3><p>DataStore required even tighter compatibility than Room. Task recovery state, preferences, and other operational values already lived in Android Preferences DataStore. Creating a new multiplatform store and starting from an empty state was not an option. An application update should not behave like a fresh install.</p><p>For a period, legacy Android code and new shared code also had to read and write the same persisted values. That made storage identity part of the migration contract. The important rules were simple:</p><pre>Same preferences file<br>Same keys<br>Same serialized representation<br>Same defaults</pre><p>The migration changed how state was accessed, not what that state meant. A simplified shared provider looked like this:</p><pre>object AppDataStoreProvider {<br>    private const val FILE_NAME = &quot;foo.preferences_pb&quot;<br>    private val dataStore: DataStore&lt;Preferences&gt; by lazy {<br>        createPreferencesDataStore(FILE_NAME)<br>    }<br>    fun createOrGetDataStore(): DataStore&lt;Preferences&gt; = dataStore<br>}</pre><p>The singleton behavior matters here. We wanted one logical DataStore instance for the same file rather than allowing different parts of the application to independently construct stores for the same persisted state.</p><p>The platform boundary itself stayed intentionally small:</p><pre>// commonMain<br>expect fun createPreferencesDataStore(fileName: String): DataStore&lt;Preferences&gt;</pre><p>Once a platform resolves the physical path, the actual DataStore creation can remain shared:</p><pre>// commonMain<br>fun getPreferencesDataStore(path: String): DataStore&lt;Preferences&gt; =<br>    PreferenceDataStoreFactory.createWithPath(<br>        corruptionHandler = ReplaceFileCorruptionHandler(<br>            produceNewData = { emptyPreferences() },<br>        ),<br>    ) {<br>        path.toPath()<br>    }</pre><h3>Android</h3><p>On Android, the platform implementation resolves the file under the application’s files directory:</p><pre>actual fun createPreferencesDataStore(fileName: String): DataStore&lt;Preferences&gt; {<br>    val path = AppContext.get().filesDir.resolve(fileName).absolutePath<br>    return getPreferencesDataStore(path)<br>}</pre><p>The critical part was keeping the file identity compatible with the existing application. If the old Android implementation wrote to one file while the new KMP implementation created another, both systems could appear healthy while operating on completely different persisted state.</p><h3>iOS</h3><p>On iOS, the same shared factory is used after resolving a platform-specific filesystem path:</p><pre>@OptIn(ExperimentalForeignApi::class)<br>actual fun createPreferencesDataStore(fileName: String): DataStore&lt;Preferences&gt; {<br>    val documentDirectory = NSFileManager.defaultManager.URLForDirectory(<br>        directory = NSDocumentDirectory,<br>        inDomain = NSUserDomainMask,<br>        appropriateForURL = null,<br>        create = false,<br>        error = null,<br>    )<br>    val path = requireNotNull(documentDirectory).path + &quot;/$fileName&quot;<br>    return getPreferencesDataStore(path)<br>}</pre><p>So the ownership split stayed narrow. The shared layer owns:</p><pre>DataStore creation<br>Corruption handling<br>Keys<br>Serialization<br>Read/write behavior<br>Storage contracts</pre><p>Platform code owns:</p><pre>Filesystem path resolution</pre><p>The preference key itself is the contract, whether the value is a flag, an enum, or a JSON blob. The key name is part of the persistence API. Renaming fooBar to something that looks cleaner, such as foo_bar, would not be a harmless refactor. Without an explicit migration, it would create a different value from DataStore&#39;s perspective.</p><p>The same applies to JSON-backed values, enums, task snapshots, timestamps, and default values. During coexistence, the real flow could look like this:</p><pre>Legacy Android code writes a preference<br>        ↓<br>KMP code reads the same preference<br>        ↓<br>CMP screen refreshes shared state<br>        ↓<br>Shared code updates persisted state<br>        ↓<br>Legacy Android code reads that state later</pre><p>That interoperability was essential during incremental migration. Old and new architecture were not isolated applications. They were two execution paths inside the same application, sharing the same operational state.</p><p>If the KMP side introduced another file, renamed a key, changed JSON representation, or silently changed a default, the two architectures could begin operating on different interpretations of the same state.</p><p>Those bugs are particularly dangerous because neither side necessarily crashes. Instead, the application starts behaving inconsistently. A preference may exist for one architecture but appear missing to another. A recovered task may look active to legacy code but absent to a CMP screen. A boolean preference may silently fall back to a different default.</p><p>That is exactly the class of failure we wanted to avoid. So the practical migration rules were stricter than the API itself:</p><ul><li>keep the existing file identity stable</li><li>reuse the same preference keys</li><li>preserve serialized formats</li><li>preserve default-value semantics</li><li>create one logical DataStore instance per file</li><li>keep path resolution platform-specific</li><li>migrate key or format changes explicitly</li><li>verify interoperability between legacy and shared callers</li></ul><p>DataStore migration was therefore mostly about preserving identity while replacing access paths. That allowed legacy Android code and new KMP code to coexist on the same persisted state.</p><h3>Gson → kotlinx.serialization</h3><p>The serialization migration followed the same principle. As long as Retrofit/Gson code and Ktor/kotlinx.serialization code could touch the same backend contracts or persisted JSON, they had to produce compatible representations. We paid particular attention to:</p><ul><li>@SerializedName and @SerialName</li><li>nullability</li><li>default values</li><li>enum values</li><li>maps</li><li>polymorphic payloads</li><li>loose JSON fields represented with JsonElement</li></ul><p>For example:</p><pre>// Before<br>data class LoginResponse(<br>    @SerializedName(&quot;foo&quot;)<br>    val foo: String?,<br>    @SerializedName(&quot;bar&quot;)<br>    val bar: Boolean?,<br>)</pre><p>became:</p><pre>@Serializable<br>data class LoginResponse(<br>    @SerialName(&quot;foo&quot;)<br>    val foo: String? = null,<br>    @SerialName(&quot;bar&quot;)<br>    val bar: Boolean? = null,<br>)</pre><p>Kotlin property naming could be improved later. Wire compatibility could not. For persisted JSON, we used the same thinking:</p><pre>val json = Json {<br>    ignoreUnknownKeys = true<br>    isLenient = true<br>}</pre><p>Writing:</p><pre>preferences[KEY_TASK_BLOB] = json.encodeToString(taskState)</pre><p>Reading:</p><pre>preferences[KEY_TASK_BLOB]?.let { json.decodeFromString&lt;TaskState&gt;(it) }</pre><p>A seemingly harmless model change could otherwise break task recovery, DataStore state, or Retrofit/Ktor parity. So we generally migrated in this order:</p><ol><li>Make the model compatible with kotlinx.serialization.</li><li>Preserve existing wire names and behavior.</li><li>Verify encode/decode behavior against known payloads.</li><li>Move the feature call sites.</li><li>Remove Gson from that path.</li></ol><h3>Retrofit → Ktor, Feature by Feature</h3><p>We moved networking gradually as well. For a period, Retrofit and Ktor both existed in production. Some feature services had already moved. Others were still using the legacy Retrofit APIs. The important requirement was that both stacks shared the same application semantics. They needed to:</p><ul><li>read authentication from the same source</li><li>use the same backend contracts</li><li>map failures consistently</li><li>avoid creating different session behavior</li></ul><p>A simplified shared Ktor provider looked like this:</p><pre>class KtorHttpProvider(<br>    private val urlConfig: UrlConfig,<br>) {<br>    private val mutex = Mutex()<br>    private var httpClient: HttpClient? = null<br>    suspend fun createOrGetHttpClient(): HttpClient {<br>        httpClient?.let { return it }<br>        return mutex.withLock {<br>            httpClient ?: HttpClient {<br>                defaultRequest {<br>                    url(urlConfig.baseUrl)<br>                    contentType(ContentType.Application.Json)<br>                }<br>                install(ContentNegotiation) {<br>                    json(Json { ignoreUnknownKeys = true })<br>                }<br>            }.also { httpClient = it }<br>        }<br>    }<br>}</pre><p>A migrated service could expose a shared contract:</p><pre>interface CourierService {<br>    suspend fun setBusy(request: SetBusyRequest): ApiResponse<br>}</pre><p>with a Ktor implementation:</p><pre>class CourierServiceImpl(<br>    private val httpProvider: KtorHttpProvider,<br>) : CourierService {<br>    override suspend fun setBusy(request: SetBusyRequest): ApiResponse {<br>        return httpProvider<br>            .createOrGetHttpClient()<br>            .put(&quot;foo/bar&quot;) { setBody(request) }<br>            .body()<br>    }<br>}</pre><p>At the same time, another feature could still use Retrofit:</p><pre>interface LegacyCourierApi {<br>    @PUT(&quot;foo/bar&quot;)<br>    suspend fun setFree(@Body request: SetFreeRequest): Response&lt;ApiResponse&gt;<br>}</pre><p>The domain layer should not care whether Ktor or Retrofit is making the request. And both stacks should still resolve authentication through the same source.</p><p>On the platform side, Ktor used OkHttp on Android and Darwin on iOS. That distinction stayed below the shared service contract.</p><p>Migrating feature by feature gave us a smaller blast radius and made it possible to compare old and new behavior under the same production conditions. It also allowed normal feature delivery to continue.</p><h3>Hilt + Koin Had to Live Together</h3><p>This is one of the more awkward parts of an incremental migration. Hilt worked well for the existing Android dependency graph, but it was not the DI model we could carry into commonMain. Koin fit the shared Kotlin modules much better.</p><p>Replacing a mature Hilt graph in one step, however, would have added unnecessary risk. So for a significant period, MDU ran both. New shared modules could move to Koin:</p><pre>val loginDataModule = module {<br>    singleOf(::LoginRepositoryImpl) { bind&lt;LoginRepository&gt;() }<br>}<br>val loginDomainModule = module {<br>    factoryOf(::LoginUseCase)<br>}<br>val loginPresenterModule = module {<br>    factoryOf(::LoginViewModel)<br>}</pre><p>CMP screens could then resolve their shared ViewModels through Koin:</p><pre>val viewModel = koinViewModel&lt;LoginViewModel&gt;()</pre><p>At the same time, existing Android entry points could remain on Hilt:</p><pre>@AndroidEntryPoint<br>class LegacyLoginFragment : Fragment() {<br>    @Inject<br>    lateinit var legacyHelper: LegacyHelper<br>}</pre><p>Having two DI frameworks in the same application was not the main problem. The real risk was having both frameworks create their own version of the same critical dependency. For example:</p><pre>two database holders<br>two socket owners<br>two service lifecycles</pre><p>That is where coexistence starts turning into split-brain architecture. So we made ownership explicit:</p><ul><li>new KMP modules defaulted to Koin</li><li>legacy Android entry points could remain Hilt-owned</li><li>dependencies crossing the two graphs required deliberate bridges</li><li>critical shared state had exactly one owner</li><li>the other graph could use that owner, but could not recreate it</li></ul><p>A tempting bridge looks like this:</p><pre>import org.koin.mp.KoinPlatformTools<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object UnsafeDatabaseBridgeModule {<br>    @Provides<br>    @Singleton<br>    fun provideTelemetryDatabase(): TelemetryDatabase {<br>        // looks short - and is wrong for Application startup<br>        return KoinPlatformTools<br>            .defaultContext()<br>            .get()<br>            .get&lt;TelemetryDatabase&gt;()<br>    }<br>}</pre><p>It is short, but it makes the Hilt graph depend on Koin already being initialized. That is especially problematic during application startup.</p><p>With @HiltAndroidApp, application member injection happens as part of super.onCreate(). In our coexistence period, startKoin() ran after that. So a Hilt binding that reaches into Koin during startup can depend on initialization order in a way that is difficult to reason about. Even if the provider is only resolved later and appears to work, ownership is still hidden behind that startup dependency.</p><p>During coexistence, there are several valid ways to bridge the two graphs. The important part is choosing one ownership direction deliberately.</p><h3>Hilt Owns, Koin Borrows</h3><p>This was the practical default while critical state still belonged to the legacy Android side. Hilt creates the shared owner. The Application receives that instance through Hilt injection. After super.onCreate(), Koin starts and registers the same instance. Koin can then use it without constructing another one.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object DatabaseModule {<br>    @Provides<br>    @Singleton<br>    fun provideTelemetryDatabase(): TelemetryDatabase {<br>        return getTelemetryDatabaseBuilder().build()<br>    }<br>}</pre><pre>@HiltAndroidApp<br>class MduApplication : Application() {<br>    @Inject<br>    lateinit var telemetryDatabase: TelemetryDatabase<br>    override fun onCreate() {<br>        super.onCreate()<br>        startKoin {<br>            androidContext(this@MduApplication)<br>            modules(<br>                module { single { telemetryDatabase } } +<br>                    kmpDataModules +<br>                    kmpDomainModules +<br>                    kmpPresenterModules<br>            )<br>        }<br>    }<br>}</pre><p>There is still only one TelemetryDatabase. Hilt owns it. Koin receives the same reference. Koin must not also declare another:</p><pre>single {<br>    getTelemetryDatabaseBuilder().build()<br>}</pre><p>That would create a second owner and defeat the purpose of the bridge.</p><h3>Koin Owns, Legacy Android Borrows</h3><p>Later in the migration, ownership may move into shared code. At that point, the direction can flip. Koin creates the shared dependency, and legacy Android code uses that same Koin-owned instance.</p><p>The important part is that Hilt does not pretend to own the dependency by recreating it. If a legacy call site needs the shared instance after Koin has already started, it can resolve it from Koin at the point of use. For example:</p><pre>val telemetryDatabase = KoinPlatform.getKoin().get&lt;TelemetryDatabase&gt;()</pre><p>Or inside a Koin-aware class:</p><pre>private val telemetryDatabase: TelemetryDatabase by inject()</pre><p>The ownership remains clear:</p><pre>Koin owns<br>    ↓<br>legacy Android borrows</pre><p>What we wanted to avoid was hiding that relationship behind a Hilt provider like the unsafe bridge shown earlier. That makes the Hilt graph look like it owns the dependency while it is actually reaching into another container. It also reintroduces the initialization-order problem.</p><h3>Create Once, Expose to Both Graphs</h3><p>Another option is to keep ownership outside both DI frameworks. The application creates the dependency once and both graphs receive the same reference. Conceptually:</p><pre>val telemetryDatabase = getTelemetryDatabaseBuilder().build()</pre><p>Koin receives it:</p><pre>startKoin {<br>    modules(<br>        module { single { telemetryDatabase } }<br>    )<br>}</pre><p>The same instance can also be exposed to legacy Android through an explicit holder or bridge. This approach adds more ceremony, but ownership is very difficult to misread:</p><pre>Application creates once<br>        ↓<br>same instance<br>   ↙           ↘<br>Hilt          Koin</pre><p>Neither graph is allowed to create another copy.</p><h3>No Bridge</h3><p>This was always the preferred option when possible. If a feature could stay entirely inside one graph, we kept it there. A CMP feature that only needed Koin did not need to involve Hilt. A legacy Android screen that still lived entirely in Hilt did not need to know about Koin.</p><p>We only bridged dependencies that genuinely had to remain singular across both worlds, such as:</p><ul><li>database ownership</li><li>socket sessions</li><li>long-lived service state</li></ul><p>Everything else could move gradually behind the strangler boundary until the bridge disappeared.</p><p>For some cross-cutting concerns, a process-wide Kotlin owner could also be simpler than connecting the two DI graphs. For example, a shared event stream:</p><pre>object NativeEvents {<br>    private val _events = MutableSharedFlow&lt;NativeEvent&gt;()<br>    val events = _events.asSharedFlow()<br>    suspend fun emit(event: NativeEvent) {<br>        _events.emit(event)<br>    }<br>}</pre><p>Both legacy Android and shared code can talk to the same object without either Hilt or Koin owning the event bus. Durable local state can use the same idea through the AppDataStoreProvider shown earlier. Both graphs can then use the same instance. Koin:</p><pre>single&lt;DataStore&lt;Preferences&gt;&gt; {<br>    AppDataStoreProvider.createOrGetDataStore()<br>}</pre><p>Hilt:</p><pre>@Provides<br>@Singleton<br>fun provideDataStore(): DataStore&lt;Preferences&gt; {<br>    return AppDataStoreProvider.createOrGetDataStore()<br>}</pre><p>Neither graph creates the DataStore independently. The provider object is the process-wide ownership boundary. Kotlin by lazy already gives us synchronized single initialization, so an additional mutex is usually unnecessary unless creation itself requires suspend-aware coordination.</p><p>We used this pattern selectively. Global objects are useful for a small number of process-wide boundaries. They should not become a replacement DI framework.</p><p>Across all of these approaches, the rule stayed the same:</p><p><strong>Two graphs may see the same owner. Neither may recreate it.</strong></p><p>So our DI migration was never about removing Hilt first. It was about keeping ownership clear while the two graphs coexisted. Hilt removal was the end of the migration, not the beginning.</p><h3>Continuing Product Development During the Migration</h3><p>The application still needed to evolve while all of this work was happening. We could not pause feature development until KMP was finished. New work generally went into the new architecture. For operationally sensitive areas, we preferred leaving the existing path alone until the new foundation was proven enough.</p><p>That did create temporary duplication. In some cases, fixes or product changes had to be implemented in both versions of a feature during the transition. It was additional work, but it kept the migration incremental.</p><p>We also kept unfinished migration work visible through internal milestones such as:</p><pre>KMPPHASE-*</pre><p>Those markers made it easier to see what had already moved, what still existed twice, and what should not yet be considered complete. That visibility mattered because coexistence is only safe when everyone knows it is coexistence.</p><h3>What the Canary Gave Us</h3><p>By the time we started placing serious CMP UI and iOS responsibility on the shared stack, Android production had already validated several assumptions.</p><p>Room Multiplatform had been exercised against real device storage behavior. Multiplatform DataStore had preserved the existing preferences contract. kotlinx.serialization had been used without changing payload semantics where parity was required. Ktor had carried production traffic while Retrofit still existed. Koin had owned shared modules next to Hilt without forcing critical state to be duplicated. And the team had continued shipping normal product work during the migration.</p><p>Those were much stronger signals than simply knowing the code compiled for iOS. What mattered was whether state survived upgrades, authentication remained coherent across old and new paths, storage still had one source of truth, and production traffic exposed hidden assumptions before another platform depended on them.</p><p>Compose Multiplatform became practical for us because the shared engine underneath it had already been exercised in production.</p><h3>Next</h3><p><a href="https://medium.com/getir/part-3-one-presenter-contract-for-two-platforms-2ff8c81057d6">Part 3</a> moves up into the presenter layer. We will look at how migrated features standardized around UIAction, UIState, and UIEvent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b86390df8e6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/part-2-strangler-fig-replacing-the-engine-while-the-app-is-running-b86390df8e6a">Part 2 — Strangler Fig: Replacing the Engine While the App Is Running</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>