<?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[Stories by John safwat on Medium]]></title>
        <description><![CDATA[Stories by John safwat on Medium]]></description>
        <link>https://medium.com/@johnsafwat362?source=rss-b9e794bb1d98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zZZr49Al1GX8F_W8</url>
            <title>Stories by John safwat on Medium</title>
            <link>https://medium.com/@johnsafwat362?source=rss-b9e794bb1d98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:08:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnsafwat362/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating Firebase into Kotlin Multiplatform (KMP): FCM, Crashlytics, and Analytics — the Native…]]></title>
            <link>https://medium.com/@johnsafwat362/integrating-firebase-into-kotlin-multiplatform-kmp-fcm-crashlytics-and-analytics-the-native-47409ea7dc92?source=rss-b9e794bb1d98------2</link>
            <guid isPermaLink="false">https://medium.com/p/47409ea7dc92</guid>
            <category><![CDATA[fcm]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[crashlytics]]></category>
            <dc:creator><![CDATA[John safwat]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 08:18:35 GMT</pubDate>
            <atom:updated>2026-06-19T08:18:35.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E27QX_uQ-T0omyN0eaTqEQ.jpeg" /></figure><h3>Integrating Firebase into Kotlin Multiplatform (KMP): FCM, Crashlytics, and Analytics — the Native Way</h3><p>Kotlin Multiplatform has matured into a serious option for teams that want to share business logic across Android and iOS without giving up native performance or platform fidelity. But the moment you try to wire up Firebase, you hit a wall that has frustrated KMP developers for years: <strong>Google does not ship an official Firebase SDK for Kotlin Multiplatform.</strong> The request has been open on Firebase’s public feature board for a long time, and as of mid-2026 it still has not landed. The official SDKs target Android (Kotlin/Java) and iOS (Swift/Objective-C) separately.</p><p>There are community wrappers that paper over this gap, but they add a dependency you do not control, lag behind native SDK releases, and only expose the subset of the API the maintainers chose to wrap. This article takes the other road: <strong>integrating Firebase using nothing but the native Android and iOS Firebase SDKs, bridged into shared code with Kotlin’s </strong><strong>expect/</strong><strong>actual mechanism.</strong> No third-party KMP libraries. You get the full native API surface, you own the integration end to end, and you upgrade on Firebase&#39;s schedule rather than someone else&#39;s.</p><p>We will cover three of the most common services — Cloud Messaging (FCM), Crashlytics, and Analytics — and the Gradle, CocoaPods, and interop plumbing that ties them together.</p><h3>The strategy: a thin shared interface over two native SDKs</h3><p>The pattern is always the same. You define a common interface in commonMain describing <em>what</em> you need — log an event, record an exception, fetch a push token. Then you write two implementations: one in androidMain that calls the Firebase Android SDK, and one in iosMain that calls the Firebase iOS SDK through Kotlin/Native&#39;s C-interop.</p><p>On iOS the key enabler is the Kotlin CocoaPods Gradle plugin. When you declare a pod(...) dependency, it generates Kotlin bindings for that pod&#39;s Objective-C API automatically. That means classes like FIRAnalytics, FIRMessaging, and FIRCrashlytics become callable directly from iosMain — no Swift bridging layer required.</p><h3>Project setup: the native prerequisites</h3><p>Whatever you do in shared code, the native Firebase SDKs still have to be present and configured per platform. There is no shortcut around this.</p><p>On <strong>Android</strong>, apply the Google services Gradle plugin and place google-services.json in your Android app module. Pull the Firebase libraries through the BoM so versions stay aligned, in the androidMain source set:</p><pre>// shared/build.gradle.kts<br>kotlin {<br>    sourceSets {<br>        androidMain.dependencies {<br>            implementation(project.dependencies.platform(&quot;com.google.firebase:firebase-bom:&lt;latest&gt;&quot;))<br>            implementation(&quot;com.google.firebase:firebase-analytics&quot;)<br>            implementation(&quot;com.google.firebase:firebase-crashlytics&quot;)<br>            implementation(&quot;com.google.firebase:firebase-messaging&quot;)<br>        }<br>    }<br>}</pre><p>On <strong>iOS</strong>, place GoogleService-Info.plist in the iOS app target and bring the Firebase pods into the Kotlin/Native build via the CocoaPods block. These pods generate the Kotlin bindings you will call from iosMain:</p><pre>kotlin {<br>    cocoapods {<br>        summary = &quot;Shared module&quot;<br>        homepage = &quot;https://example.com&quot;<br>        ios.deploymentTarget = &quot;15.0&quot;<br><br>        pod(&quot;FirebaseCore&quot;)<br>        pod(&quot;FirebaseMessaging&quot;)<br>        pod(&quot;FirebaseCrashlytics&quot;)<br>        pod(&quot;FirebaseAnalytics&quot;)<br>    }<br>}</pre><p>Check Maven Central and the Firebase release notes for current versions rather than pinning a number from a blog post.</p><blockquote><strong><em>Pitfall #1:</em></strong><em> Do not declare the same Firebase pods in </em>both<em> your </em><em>iosApp/Podfile and the shared module&#39;s </em><em>cocoapods block. Duplicate pod declarations cause linker errors and version conflicts that are painful to diagnose. Let the shared module own the pods, and integrate that module into the iOS app.</em></blockquote><h3>Initializing Firebase with expect/actual</h3><p>Firebase has to be initialized before any service is used, and the platforms differ. Android auto-initializes through a content provider (or an explicit FirebaseApp.initializeApp(context)), while iOS calls FirebaseApp.configure(), conventionally from the app delegate. This asymmetry is the textbook case for expect/actual.</p><pre>// commonMain<br>expect fun initializeFirebase()</pre><pre>// androidMain<br>import com.google.firebase.FirebaseApp<br><br>actual fun initializeFirebase() {<br>    FirebaseApp.initializeApp(appContext)<br>}</pre><pre>// iosMain<br>import cocoapods.FirebaseCore.FIRApp<br><br>actual fun initializeFirebase() {<br>    FIRApp.configure()<br>}</pre><pre>// Alternatively, configure from the iOS AppDelegate<br>import FirebaseCore<br><br>class AppDelegate: NSObject, UIApplicationDelegate {<br>    func application(_ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -&gt; Bool {<br>        FirebaseApp.configure()<br>        return true<br>    }<br>}</pre><h3>Analytics: the simplest bridge</h3><p>Analytics is fire-and-forget logging, which makes it the gentlest introduction to the pattern. Define the common surface, then implement it twice against the native APIs.</p><pre>// commonMain<br>expect object AppAnalytics {<br>    fun logEvent(name: String, params: Map&lt;String, String&gt; = emptyMap())<br>}</pre><pre>// androidMain<br>import com.google.firebase.analytics.FirebaseAnalytics<br>import android.os.Bundle<br><br>actual object AppAnalytics {<br>    actual fun logEvent(name: String, params: Map&lt;String, String&gt;) {<br>        val bundle = Bundle().apply { params.forEach { (k, v) -&gt; putString(k, v) } }<br>        FirebaseAnalytics.getInstance(appContext).logEvent(name, bundle)<br>    }<br>}</pre><pre>// iosMain<br>import cocoapods.FirebaseAnalytics.FIRAnalytics<br><br>actual object AppAnalytics {<br>    actual fun logEvent(name: String, params: Map&lt;String, String&gt;) {<br>        FIRAnalytics.logEventWithName(name, params as Map&lt;Any?, *&gt;)<br>    }<br>}</pre><h3>Crashlytics: sharing crash reporting</h3><p>The same shape applies to Crashlytics. Expose logging and exception recording from common code.</p><pre>// commonMain<br>expect object AppCrashlytics {<br>    fun log(message: String)<br>    fun recordException(error: Throwable)<br>}</pre><pre>// androidMain<br>import com.google.firebase.crashlytics.FirebaseCrashlytics<br><br>actual object AppCrashlytics {<br>    actual fun log(message: String) =<br>        FirebaseCrashlytics.getInstance().log(message)<br>    actual fun recordException(error: Throwable) =<br>        FirebaseCrashlytics.getInstance().recordException(error)<br>}</pre><pre>// iosMain<br>import cocoapods.FirebaseCrashlytics.FIRCrashlytics<br>import platform.Foundation.NSError<br><br>actual object AppCrashlytics {<br>    actual fun log(message: String) =<br>        FIRCrashlytics.crashlytics().log(message)<br>    actual fun recordException(error: Throwable) {<br>        val nsError = NSError.errorWithDomain(&quot;KotlinException&quot;, 0, mapOf(&quot;reason&quot; to (error.message ?: &quot;&quot;)))<br>        FIRCrashlytics.crashlytics().recordError(nsError)<br>    }<br>}</pre><blockquote><strong><em>Pitfall #2:</em></strong><em> On iOS, Crashlytics only produces symbolicated reports if dSYM files are uploaded to Firebase. With a KMP shared framework you have </em>two<em> crash sources — Swift/Obj-C and the Kotlin/Native framework — and both need dSYMs uploaded. Ensure the Crashlytics dSYM upload run-script phase runs and that Kotlin/Native produces debug symbols, or your Kotlin crashes will surface as unreadable addresses. Note also that Kotlin exceptions crossing the interop boundary do not map cleanly to native stack traces, so logging breadcrumbs before risky calls pays off.</em></blockquote><h3>Cloud Messaging: where the native lifecycle bites</h3><p>FCM is the hardest of the three because push is deeply tied to each platform’s lifecycle. Android delivers messages through a FirebaseMessagingService; iOS routes them through UNUserNotificationCenter and APNs, requires runtime notification permission, and needs an APNs key configured in the Firebase console. None of that disappears — but the parts you <em>can</em> share, like fetching the registration token, fit the same expect/actual shape.</p><pre>// commonMain<br>expect suspend fun firebaseToken(): String?</pre><pre>// androidMain<br>import com.google.firebase.messaging.FirebaseMessaging<br>import kotlinx.coroutines.tasks.await<br><br>actual suspend fun firebaseToken(): String? =<br>    FirebaseMessaging.getInstance().token.await()</pre><pre>// iosMain<br>import cocoapods.FirebaseMessaging.FIRMessaging<br>import kotlin.coroutines.resume<br>import kotlinx.coroutines.suspendCancellableCoroutine<br><br>actual suspend fun firebaseToken(): String? =<br>    suspendCancellableCoroutine { cont -&gt;<br>        FIRMessaging.messaging().tokenWithCompletion { token, _ -&gt;<br>            cont.resume(token)<br>        }<br>    }</pre><p>The message-receiving side stays native. On Android you subclass FirebaseMessagingService and forward payloads into shared code; on iOS you implement the UNUserNotificationCenterDelegate and FIRMessagingDelegate callbacks in the app target. This is correct, not a workaround — push handling belongs in each platform&#39;s lifecycle.</p><blockquote><strong><em>Pitfall #3:</em></strong><em> Push notifications silently fail on iOS if the APNs authentication key is not uploaded to the Firebase console, or if you test on the simulator. Always validate on a physical device with a provisioning profile that includes the Push Notifications capability. On Android 13+ (API 33), </em><em>POST_NOTIFICATIONS is a runtime permission — fetching a token is not enough if the user never granted permission to display anything.</em></blockquote><h3>Common cross-cutting pitfalls</h3><p>A few issues recur in every native Firebase-in-KMP project. Keep the Android BoM and the iOS pod versions deliberately aligned; drift between them produces confusing runtime failures. CocoaPods integration is the most common source of build breakage, so when you hit linker errors run pod repo update and re-run the podInstall Gradle task before assuming the Kotlin is at fault. And remember that the generated iOS bindings expose Objective-C names (FIRAnalytics, tokenWithCompletion, completion handlers instead of suspend functions) — wrapping those callbacks into idiomatic Kotlin coroutines in your actual implementations keeps the common API clean.</p><h3>Conclusion</h3><p>Firebase still has no first-party Kotlin Multiplatform SDK, but you do not need a third-party one to ship cleanly. Keep the native Firebase SDKs configured per platform, define thin expect interfaces in commonMain, and implement them against the Firebase Android SDK and — through the CocoaPods-generated bindings — the Firebase iOS SDK. Analytics and Crashlytics collapse into a few lines each; FCM keeps its message-receiving lifecycle on the native side where it belongs while still sharing the token and topic logic. The payoff is full control: the complete native API surface, upgrades on Firebase&#39;s schedule, and zero dependencies you did not write. Configure the native layer correctly, respect each platform&#39;s notification and symbol-upload lifecycle, and you can share the overwhelming majority of your Firebase code while shipping a fully native experience on both platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47409ea7dc92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose Multiplatform (CMP): One UI Codebase for Android, iOS, Desktop, and Web]]></title>
            <link>https://medium.com/@johnsafwat362/compose-multiplatform-cmp-one-ui-codebase-for-android-ios-desktop-and-web-fb57da7bac35?source=rss-b9e794bb1d98------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb57da7bac35</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[compo]]></category>
            <dc:creator><![CDATA[John safwat]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 22:03:30 GMT</pubDate>
            <atom:updated>2026-04-24T22:03:30.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*902wZtcuygM4HYzaV2bmUw.png" /></figure><blockquote>A practical guide to JetBrains’ declarative UI framework from your first @Composable to advanced animations and platform-specific interop.</blockquote><p>For years, cross-platform UI development has been a series of trade-offs. You either embraced the compromise of a web view wrapped in native shell (hello, Cordova), accepted a JavaScript bridge and its performance ceiling (React Native), or built everything twice and prayed your designers didn’t ask for “just one more small change.”</p><p>Then JetBrains did something quietly radical. They took Google’s modern Android UI toolkit, Jetpack Compose, and asked: <em>what if this ran everywhere?</em></p><p>That’s <strong><em>Compose Multiplatform (CMP)</em></strong> and in 2026, it’s arguably the most pragmatic way to ship a truly native UI from a single Kotlin codebase. Let’s dig in.</p><h3>1. Introduction to Compose Multiplatform</h3><h3>What is CMP?</h3><p>Compose Multiplatform is a <strong>declarative UI framework</strong> built and maintained by JetBrains, layered directly on top of Google’s Jetpack Compose for Android. If you’ve written Jetpack Compose, you already know roughly 90% of CMP. The same @Composable functions, the same Modifier chains, the same state model — just extended to run on iOS, Desktop (JVM), and Web (Wasm/JS).</p><p>Think of it this way: Jetpack Compose is the engine. CMP is the adapter kit that lets that engine drive every platform you care about.</p><h3>The Problem It Solves</h3><p>Kotlin Multiplatform (KMP) has been a hit among teams who wanted to share business logic — networking, database access, domain layers, use cases — across Android and iOS. But the UI layer? That was still two codebases: Jetpack Compose on Android, SwiftUI or UIKit on iOS, plus whatever you were doing for desktop and web.</p><p>CMP closes that gap. You can now share the <strong>entire UI layer</strong> across:</p><ul><li><strong>Android</strong> (via Jetpack Compose — nothing exotic, it’s the same stack)</li><li><strong>iOS</strong> (rendered to a UIViewController you embed in your iOS app)</li><li><strong>Desktop</strong> (macOS, Windows, Linux — runs on the JVM)</li><li><strong>Web</strong> (Wasm is the current flagship target; JS/Canvas is also supported)</li></ul><p>For many apps, this takes UI code reuse from ~0% to well over 90%.</p><h3>“But Isn’t This Just a Web View?”</h3><p>No. This is the most important misconception to squash up front.</p><p>CMP is <strong>not</strong> a JavaScript bridge. It is not a web view wrapper. It is not interpreting JSX at runtime.</p><ul><li>On <strong>Android</strong>, CMP uses the native Jetpack Compose engine. It draws directly to the Android rendering pipeline.</li><li>On <strong>iOS and Desktop</strong>, CMP uses <strong>Skia</strong> — the same hardware-accelerated 2D graphics library that powers Chrome, Flutter, and Android itself. On iOS specifically, Skia is wired into <strong>Metal</strong>, Apple’s low-level GPU API.</li><li>On <strong>Web (Wasm)</strong>, it renders via Skia to an HTML canvas, again with hardware acceleration.</li></ul><p>This is native performance with a shared codebase. Scrolling is smooth. Animations hit 60 (or 120) fps. There is no JavaScript event loop between your code and the pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSY4V7QsJZAuev1KyD8dtA.webp" /></figure><h3>2. Core Concepts: The Declarative Paradigm</h3><p>Before touching code, you need a mindset shift — especially if you’re coming from UIKit, XML-based Android views, or even older web frameworks.</p><h3>State-Driven UI</h3><p>In imperative UI, you <em>tell</em> the framework what to do: textView.setText(&quot;Hello&quot;), button.isEnabled = false, view.backgroundColor = .red. You&#39;re reaching into the UI tree and mutating things.</p><p>In CMP, the UI is a <strong>function of state</strong>. You never call textView.setText(). You update a variable, and the framework redraws whatever needs redrawing.</p><pre>@Composable<br>fun Greeting(name: String) {<br>    Text(&quot;Hello, $name&quot;)<br>}</pre><p>If name changes, Greeting re-runs and the new text appears. No manual updates. No stale references. No &quot;I forgot to call reloadData().&quot;</p><h3>Composition and Recomposition</h3><p>When your app starts, CMP walks your @Composable functions and builds a tree of UI nodes. This first pass is called the <strong>Composition</strong>.</p><p>When state changes, CMP doesn&#39;t tear down and rebuild the whole tree. It performs <strong>Recomposition</strong> — surgically re-running only the composables whose inputs changed, and updating only the nodes affected. This is why Compose feels fast even when the UI is complex: the framework is doing the minimum work required.</p><p>Understanding this is what separates &quot;Compose tourists&quot; from &quot;Compose residents.&quot; If you write composables that recompose on every keystroke when only one text field changed, you&#39;ll ship a laggy app. Keep state narrow. Pass only what each composable needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98C7NFCE7xfp8BLUrUN2Nw.png" /></figure><h3>The @Composable Annotation</h3><p>Every UI-producing function in CMP is annotated with @Composable. This tells the compiler plugin: <em>this function doesn&#39;t return a value — it emits UI into the current composition.</em></p><pre>@Composable<br>fun WelcomeScreen() {<br>    Text(&quot;Welcome!&quot;)<br>    Button(onClick = { /* ... */ }) {<br>        Text(&quot;Get started&quot;)<br>    }<br>}</pre><p>@Composable functions can only be called from other @Composable functions. The compiler enforces this. It&#39;s not magic — it&#39;s a very disciplined form of metaprogramming.</p><h3>3. How to Build a UI in CMP</h3><p>Let’s move from theory to screen.</p><h3>Basic Components</h3><p>CMP ships with a rich set of foundational and Material components. The ones you’ll use constantly:</p><pre>Text(&quot;A simple label&quot;)<br><br>Button(onClick = { println(&quot;clicked&quot;) }) {<br>    Text(&quot;Tap me&quot;)<br>}<br><br>Image(<br>    painter = painterResource(&quot;icon.png&quot;),<br>    contentDescription = &quot;App logo&quot;<br>)<br><br>Icon(<br>    imageVector = Icons.Default.Favorite,<br>    contentDescription = &quot;Favorite&quot;<br>)</pre><p>No XML, no storyboards, no Interface Builder. UI is code — typed, refactorable, and diffable in your PRs.</p><h3>Layout Systems</h3><p>CMP’s layout primitives are small in number and large in expressiveness:</p><ul><li><strong>Column</strong> — stacks children vertically.</li><li><strong>Row</strong> — lays them out horizontally.</li><li><strong>Box</strong> — places children on top of each other (z-stack).</li><li><strong>LazyColumn / </strong><strong>LazyRow</strong> — efficient scrolling lists. Only the visible items are composed. This is the CMP equivalent of Android&#39;s RecyclerView or iOS&#39;s UITableView / UICollectionView.</li></ul><pre>LazyColumn {<br>    items(messages) { message -&gt;<br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(16.dp)<br>        ) {<br>            Avatar(message.sender)<br>            Column {<br>                Text(message.sender.name, style = MaterialTheme.typography.titleSmall)<br>                Text(message.body)<br>            }<br>        }<br>    }<br>}</pre><p>If you’ve fought with RecyclerView adapters or UITableViewDataSource protocols, the LazyColumn block above will feel like cheating.</p><h3>Modifiers: The Secret Sauce</h3><p>Modifiers are how you style, size, position, and attach behavior to any composable. They chain left-to-right, and order matters.</p><pre>Box(<br>    modifier = Modifier<br>        .size(120.dp)<br>        .background(Color.Blue, shape = RoundedCornerShape(16.dp))<br>        .clickable { println(&quot;tapped the box&quot;) }<br>        .padding(16.dp)<br>        .shadow(elevation = 8.dp)<br>)</pre><p>Padding before background draws padding inside the background. Padding after background draws padding around it. That’s the mental model.</p><p>Modifiers handle: sizing, padding, margins, borders, shadows, click handlers, focus, drag gestures, semantics for accessibility, and much more. Most of your styling work happens here.</p><h3>State Management</h3><p>State in CMP is a first-class citizen. The two APIs you’ll use every day:</p><pre>@Composable<br>fun Counter() {<br>    var count by remember { mutableStateOf(0) }<br>    Column {<br>        Text(&quot;Count: $count&quot;)<br>        Button(onClick = { count++ }) {<br>            Text(&quot;Increment&quot;)<br>        }<br>    }<br>}</pre><p>Two things happening here:</p><ul><li><strong>mutableStateOf</strong> creates an observable state holder. When its value changes, anything reading it recomposes.</li><li><strong>remember</strong> tells Compose to keep this value across recompositions. Without it, you&#39;d create a fresh 0 on every re-run and the counter would never increment.</li></ul><p>For state that needs to survive configuration changes (rotations on Android, window resizes on desktop), use rememberSaveable. For state hoisted up to a ViewModel or shared across screens, combine CMP&#39;s state APIs with your favorite state container — MVVM, MVI, or a KMP-friendly library like decompose or voyager.</p><h3>4. Animation in CMP</h3><p>Animations in Compose are one of the framework’s quiet superpowers. Because they’re state-driven like the rest of the UI, they’re composable in every sense of the word. Let’s walk up the complexity ladder.</p><h3>High-Level “Drop-In” Animations</h3><p>Start here. Ninety percent of product animation needs are covered by three APIs.</p><p><strong>AnimatedVisibility</strong> — animate a composable in or out:</p><pre>AnimatedVisibility(<br>    visible = isExpanded,<br>    enter = fadeIn() + slideInVertically(),<br>    exit = fadeOut() + slideOutVertically()<br>) {<br>    DetailsPanel()<br>}</pre><p>Flip isExpanded, and the panel fades and slides on its way in and out. No animation bookkeeping required.</p><p><strong>animateContentSize()</strong> — smoothly animate a container when its contents grow or shrink:</p><pre>Column(modifier = Modifier.animateContentSize()) {<br>    Text(headline)<br>    if (expanded) {<br>        Text(longDescription)<br>    }<br>}</pre><p>Toggle expanded and the column smoothly stretches to accommodate the new content. No layout flicker, no manual height calculations.</p><p><strong>AnimatedContent</strong> — crossfade between entirely different composables based on state:</p><pre>AnimatedContent(targetState = screenState) { state -&gt;<br>    when (state) {<br>        is Loading -&gt; LoadingSpinner()<br>        is Success -&gt; ResultView(state.data)<br>        is Error -&gt; ErrorMessage(state.message)<br>    }<br>}</pre><h3>Property-Based Animations: animate*AsState</h3><p>When you want to animate a single value smoothly, the animate*AsState family has you covered:</p><pre>val color by animateColorAsState(<br>    targetValue = if (isActive) Color.Green else Color.Gray<br>)<br><br>val elevation by animateDpAsState(<br>    targetValue = if (isPressed) 2.dp else 8.dp<br>)<br><br>val rotation by animateFloatAsState(<br>    targetValue = if (isOpen) 180f else 0f<br>)</pre><p>Read the animated value in your composable, apply it via Modifier or a property, and the framework interpolates between values whenever targetValue changes.</p><h3>Complex and Coordinated Animations</h3><p><strong>updateTransition</strong> lets you orchestrate multiple animations that all key off the same state change:</p><pre>val transition = updateTransition(targetState = selected, label = &quot;card&quot;)<br>val bgColor by transition.animateColor { if (it) Color.Blue else Color.White }<br>val padding by transition.animateDp { if (it) 24.dp else 16.dp }<br>val scale by transition.animateFloat { if (it) 1.05f else 1f }</pre><p>Every property changes in lockstep, on the same timeline, and you can tune each curve independently.</p><p><strong>InfiniteTransition</strong> is for looping animations — loading spinners, pulsing indicators, idle states:</p><pre>val infinite = rememberInfiniteTransition()<br>val alpha by infinite.animateFloat(<br>    initialValue = 0.3f,<br>    targetValue = 1f,<br>    animationSpec = infiniteRepeatable(<br>        animation = tween(800),<br>        repeatMode = RepeatMode.Reverse<br>    )<br>)</pre><h3>Performance Considerations</h3><p>One warning: animations recompose the parts of your UI that read them, often at 60+ fps. Over-recomposition is the number-one performance footgun in CMP.</p><p>A few rules that will save you pain:</p><ul><li><strong>Prefer the built-in animation APIs.</strong> They’re tuned for the Skia rendering pipeline and skip as many layers of the composition as possible. Don’t build your own tick loop with LaunchedEffect and a while loop unless you have a very specific reason.</li><li><strong>Read animated values as late as possible.</strong> If only a leaf node needs the animated color, don’t destructure it at the top of a huge composable where it’ll force the whole subtree to recompose.</li><li><strong>Use the Layout Inspector and Compose Compiler reports.</strong> They’ll tell you which composables are recomposing more than they should.</li></ul><p>Get those right and CMP animations will run butter-smooth on every target.</p><h3>5. Advanced Considerations</h3><p>Two topics separate hobby projects from production apps.</p><h3>Platform-Specific Code with expect / actual</h3><p>Not everything makes sense to share. Sometimes you want a <strong>native</strong> experience — an Apple Map on iOS, a Google Map on Android, a system file picker on desktop. KMP’s expect / actual mechanism, inherited by CMP, handles this cleanly.</p><p>In your <strong>common</strong> source set, declare what you need:</p><pre>// commonMain<br>@Composable<br>expect fun MapView(location: LatLng, modifier: Modifier = Modifier)</pre><p>In <strong>androidMain</strong>, implement with Google Maps:</p><pre>@Composable<br>actual fun MapView(location: LatLng, modifier: Modifier) {<br>    GoogleMap(<br>        modifier = modifier,<br>        cameraPositionState = rememberCameraPositionState {<br>            position = CameraPosition.fromLatLngZoom(location.toGms(), 14f)<br>        }<br>    )<br>}</pre><p>In <strong>iosMain</strong>, use MapKit via Compose’s UIKit interop:</p><pre>@Composable<br>actual fun MapView(location: LatLng, modifier: Modifier) {<br>    UIKitView(<br>        factory = {<br>            MKMapView().apply {<br>                setRegion(/* ... */, animated = true)<br>            }<br>        },<br>        modifier = modifier<br>    )<br>}</pre><p>Same composable name, same call site, platform-appropriate implementation. Your feature code never has to know.</p><h3>Interoperability with SwiftUI and UIKit</h3><p>One of the most underrated CMP features is that interop runs both ways.</p><p>You can <strong>embed SwiftUI or UIKit views inside CMP</strong> (via UIKitView and UIKitViewController on iOS) — useful when Apple ships something CMP doesn&#39;t wrap yet, like certain ARKit or VisionKit components.</p><p>And critically, you can <strong>embed CMP inside an existing iOS app</strong>. CMP exports a UIViewController from your shared module; your iOS app can present it like any other VC. This means migration doesn&#39;t have to be all-or-nothing. Ship one screen in CMP. Then another. Then a feature. Then the whole app.</p><p>That gradual path is, in my experience, the single biggest reason teams stick with CMP versus bouncing back to maintaining two UI codebases.</p><h3>Wrapping Up</h3><p>Compose Multiplatform isn’t “React Native for Kotlin.” It’s something more ambitious: a single declarative UI framework that renders natively on every major platform, backed by the same battle-tested engine Google ships on a billion Android phones.</p><p>If you’ve got a Kotlin backend, a Jetpack Compose Android app, or a KMP project already sharing business logic — CMP is a short step, not a leap. And if you’re starting fresh, it’s one of the most productive UI stacks available today.</p><p>Start small. Port one screen. Get a feel for the state model. Wire up a few animations. Before long, you’ll be shipping pixel-identical UI to Android, iOS, Desktop, and Web from the same commonMain folder — and wondering how you ever did it any other way.</p><p>Happy composing.</p><p><em>If you found this useful, a few claps help it find other developers staring at two UI codebases and wondering if there’s a better way. There is.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb57da7bac35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Multiplatform in 2026: The Developer’s Deep Dive into KMP vs Native vs Flutter]]></title>
            <link>https://medium.com/@johnsafwat362/kotlin-multiplatform-in-2026-the-developers-deep-dive-into-kmp-vs-native-vs-flutter-ada63a569597?source=rss-b9e794bb1d98------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada63a569597</guid>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[John safwat]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 16:06:05 GMT</pubDate>
            <atom:updated>2026-04-17T16:06:05.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UagHft7pi1RLZvc1OkW8Jw.png" /></figure><h4><strong>Why This Article?</strong></h4><p>Cross-platform mobile development has always been a compromise game. You pick your poison: give up platform fidelity, fight a framework’s abstraction layer, or write everything twice. Kotlin Multiplatform (KMP) enters this conversation with a different thesis entirely — <strong><em>share only the logic, own the UI</em></strong>.</p><p>If you’ve shipped production Android apps, dabbled in iOS, or evaluated Flutter and walked away unsatisfied, this article is for you. We’ll go deep on architecture, do an honest comparison, and build a real shared module from scratch.</p><h3>What Is Kotlin Multiplatform?</h3><p>KMP is a Kotlin compiler feature — not a framework — that lets you compile Kotlin code to multiple targets: JVM (Android), Native (iOS, macOS, Linux, Windows), JavaScript, and WebAssembly.</p><p>The key distinction is <strong>what KMP shares</strong>:</p><ul><li>✅ Business logic</li><li>✅ Data models</li><li>✅ Networking (via Ktor)</li><li>✅ Local persistence (via SQLDelight)</li><li>✅ ViewModels / state management</li><li>❌ UI (by default — unless you use Compose Multiplatform)</li></ul><p>JetBrains officially declared KMP <strong>stable</strong> in November 2023. Google has been co-investing since 2022. It’s not a toy anymore.</p><h3>The Kotlin/Native Compiler Under the Hood</h3><p>When you target iOS, Kotlin code is compiled via the <strong>Kotlin/Native</strong> backend using LLVM to produce a native binary (.framework or .xcframework). This means:</p><ul><li>No JVM on iOS</li><li>No bridge overhead at runtime</li><li>Direct interoperability with Swift/Objective-C through generated headers</li><li>The shared module runs as native ARM64 code</li></ul><pre>Kotlin Source (.kt)<br>       │<br>       ├──▶ Kotlin/JVM (Android) ──▶ .class / .dex<br>       │<br>       └──▶ Kotlin/Native (iOS) ──▶ LLVM IR ──▶ .xcframewor</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wZ-ERRcZXX65NNebUZD6A.png" /></figure><h3>The Honest Comparison — Native vs Flutter vs KMP</h3><h3>2.1 Fully Native (Swift + Kotlin)</h3><p><strong>How it works:</strong> You maintain two entirely separate codebases — Swift/SwiftUI for iOS and Kotlin/Jetpack Compose for Android.</p><p><strong>Pros:</strong></p><ul><li>100% platform fidelity</li><li>First-party tooling and no abstraction gaps</li><li>Immediate access to new OS APIs the day they ship</li><li>Best debugging experience</li></ul><p><strong>Cons:</strong></p><ul><li>Two teams (or one team context-switching constantly)</li><li>Logic bugs fixed twice</li><li>Feature velocity halved unless you have enormous resources</li></ul><p><strong>When to choose it:</strong> Safety-critical apps (banking, healthcare), apps that are deeply OS-integrated (widgets, live activities, watch apps), or when your teams are already organized by platform.</p><h3>2.2 Flutter</h3><p><strong>How it works:</strong> Dart code compiles to native ARM. Flutter brings its own rendering engine (Impeller/Skia) and draws every pixel itself — the platform only provides a canvas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*psKR2pFCKwCGYPeDuC1cmA.png" /></figure><p><strong>Pros:</strong></p><ul><li>Single codebase for UI <em>and</em> logic</li><li>Very fast development cycle (hot reload)</li><li>Consistent pixel-perfect UI across platforms</li><li>Strong ecosystem, backed by Google</li><li>Excellent for design-heavy, brand-controlled UIs</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Custom rendering means custom everything.</strong> Platform components (system pickers, keyboard behaviors, accessibility traits) must be shimmed or rebuilt</li><li>Platform channels (Dart ↔ Native) are a real pain point for deep integrations</li><li>Dart is yet another language investment — your Android/iOS teams need retraining</li><li>App size overhead from the embedded engine</li><li>iOS scroll physics, text selection, and keyboard handling have historically felt “off”</li></ul><p><strong>When to choose it:</strong> Startups wanting one team, content-driven apps, apps where visual consistency across platforms is the top priority, or when your team doesn’t have iOS/Android specialists.</p><h3>2.3 Kotlin Multiplatform (KMP)</h3><p><strong>How it works:</strong> You write shared Kotlin for logic. Each platform team writes their UI natively using the tools they already know (SwiftUI, Compose). The shared module is consumed as a native library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxM2f7_RbNvTy5Cr8SihAg.png" /></figure><p><strong>Pros:</strong></p><ul><li><strong>Zero compromise on UI</strong> — SwiftUI on iOS, Compose on Android</li><li>Native performance (no bridge, no runtime overhead)</li><li>iOS devs still write Swift; Android devs still write Kotlin</li><li>Gradual adoption — you can share one layer at a time</li><li>Coroutines + Flow work across platforms (with Swift wrappers)</li><li>Strong interop with Swift/Objective-C</li></ul><p><strong>Cons:</strong></p><ul><li>Requires competency in <em>both</em> platforms — you still have two UI codebases</li><li>Swift concurrency interop with suspend functions has rough edges (improving with SKIE)</li><li>Kotlin/Native compilation is slow (incremental builds help)</li><li>Smaller ecosystem than Flutter (though growing fast)</li><li>expect/actual can become messy if overused</li></ul><p><strong>When to choose it:</strong> Teams that already have Android/iOS expertise, apps requiring deep platform integration, projects where you want to unify business logic without surrendering native UI quality.</p><h3>KMP Architecture Deep Dive</h3><h3>The expect / actual Mechanism</h3><p>This is KMP’s core abstraction. You declare an expect declaration in commonMain — a contract — and provide actualimplementations per platform.</p><pre>// the shared code <br>// commonMain/Platform.kt<br>expect class Platform() {<br>    val name: String<br>}<br><br>expect fun randomUUID(): String</pre><pre>// the android native code implementation <br>// androidMain/Platform.android.kt<br>actual class Platform actual constructor() {<br>    actual val name: String = &quot;Android ${Build.VERSION.SDK_INT}&quot;<br>}<br><br>actual fun randomUUID(): String = java.util.UUID.randomUUID().toString()</pre><pre>// the IOS native code implementation<br>// iosMain/Platform.ios.kt<br>import platform.UIKit.UIDevice<br><br>actual class Platform actual constructor() {<br>    actual val name: String = <br>        UIDevice.currentDevice.systemName() + &quot; &quot; + <br>        UIDevice.currentDevice.systemVersion<br>}<br><br>actual fun randomUUID(): String = platform.Foundation.NSUUID().UUIDString()</pre><h3>Source Set Hierarchy</h3><p>A typical KMP project has this source set layout:</p><pre>src/<br>├── commonMain/       ← shared code, all targets<br>├── commonTest/       ← shared tests<br>├── androidMain/      ← Android-specific actuals<br>├── androidUnitTest/<br>├── iosMain/          ← iOS-specific actuals<br>└── iosTest/</pre><h3>Getting Started — Full Walkthrough</h3><p>We’ll build a <strong>WeatherRepository</strong> that fetches data from a public API, caches it locally, and exposes a reactive stream. This covers: networking, serialization, local DB, and coroutine-based state.</p><h3>4.1 Prerequisites</h3><ul><li>Android Studio Hedgehog+ (with KMP plugin) or IntelliJ IDEA</li><li>Xcode 15+</li><li>JDK 17+</li><li>Kotlin 2.0+</li></ul><h3>4.2 Create the Project</h3><p>Use the <a href="https://kmp.jetbrains.com/">KMP Wizard</a> or the IDE plugin. Select:</p><ul><li><strong>Android + iOS</strong> targets</li><li><strong>Share business logic</strong> (not UI)</li></ul><p>This scaffolds the project. Your build.gradle.kts (shared module) will look like:</p><pre>// shared/build.gradle.kts<br>plugins {<br>    alias(libs.plugins.kotlinMultiplatform)<br>    alias(libs.plugins.androidLibrary)<br>    alias(libs.plugins.kotlinSerialization)<br>    alias(libs.plugins.sqlDelight)<br>}<br><br>kotlin {<br>    androidTarget {<br>        compilations.all {<br>            kotlinOptions { jvmTarget = &quot;17&quot; }<br>        }<br>    }<br>    listOf(<br>        iosX64(),<br>        iosArm64(),<br>        iosSimulatorArm64()<br>    ).forEach { iosTarget -&gt;<br>        iosTarget.binaries.framework {<br>            baseName = &quot;Shared&quot;<br>            isStatic = true<br>        }<br>    }<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(libs.ktor.client.core)<br>            implementation(libs.ktor.client.content.negotiation)<br>            implementation(libs.ktor.serialization.kotlinx.json)<br>            implementation(libs.kotlinx.coroutines.core)<br>            implementation(libs.kotlinx.serialization.json)<br>            implementation(libs.sqldelight.runtime)<br>        }<br>        androidMain.dependencies {<br>            implementation(libs.ktor.client.okhttp)<br>            implementation(libs.sqldelight.android.driver)<br>        }<br>        iosMain.dependencies {<br>            implementation(libs.ktor.client.darwin)<br>            implementation(libs.sqldelight.native.driver)<br>        }<br>    }<br>}</pre><h3>4.3 Define Your Data Models</h3><pre>// commonMain/data/model/Weather.kt<br>import kotlinx.serialization.SerialName<br>import kotlinx.serialization.Serializable<br><br>@Serializable<br>data class WeatherResponse(<br>    @SerialName(&quot;name&quot;) val city: String,<br>    @SerialName(&quot;main&quot;) val main: MainWeather,<br>    @SerialName(&quot;weather&quot;) val conditions: List&lt;WeatherCondition&gt;<br>)<br>@Serializable<br>data class MainWeather(<br>    @SerialName(&quot;temp&quot;) val temperature: Double,<br>    @SerialName(&quot;humidity&quot;) val humidity: Int<br>)<br>@Serializable<br>data class WeatherCondition(<br>    @SerialName(&quot;description&quot;) val description: String,<br>    @SerialName(&quot;icon&quot;) val icon: String<br>)</pre><h3>4.4 Networking with Ktor</h3><pre>// commonMain/data/remote/WeatherApi.kt<br>import io.ktor.client.*<br>import io.ktor.client.call.*<br>import io.ktor.client.plugins.contentnegotiation.*<br>import io.ktor.client.request.*<br>import io.ktor.serialization.kotlinx.json.*<br>import kotlinx.serialization.json.Json<br><br>class WeatherApi(private val client: HttpClient) {<br>    suspend fun getWeather(city: String, apiKey: String): WeatherResponse {<br>        return client.get(&quot;https://api.openweathermap.org/data/2.5/weather&quot;) {<br>            parameter(&quot;q&quot;, city)<br>            parameter(&quot;appid&quot;, apiKey)<br>            parameter(&quot;units&quot;, &quot;metric&quot;)<br>        }.body()<br>    }<br>}<br><br>// commonMain/di/HttpClientFactory.kt<br>fun createHttpClient(): HttpClient = HttpClient {<br>    install(ContentNegotiation) {<br>        json(Json {<br>            ignoreUnknownKeys = true<br>            isLenient = true<br>        })<br>    }<br>}</pre><h3>4.5 Local Persistence with SQLDelight</h3><p>Define your schema in a .sq file:</p><pre>-- commonMain/sqldelight/com/yourapp/db/WeatherCache.sq</pre><pre>CREATE TABLE WeatherCache (<br>    city TEXT NOT NULL PRIMARY KEY,<br>    temperature REAL NOT NULL,<br>    humidity INTEGER NOT NULL,<br>    description TEXT NOT NULL,<br>    cached_at INTEGER NOT NULL<br>);</pre><pre>getWeatherByCity:<br>SELECT * FROM WeatherCache WHERE city = :city;</pre><pre>insertOrReplace:<br>INSERT OR REPLACE INTO WeatherCache(city, temperature, humidity, description, cached_at)<br>VALUES (?, ?, ?, ?, ?);</pre><pre>deleteOlderThan:<br>DELETE FROM WeatherCache WHERE cached_at &lt; :threshold;</pre><p>Database Driver factory using expect/actual:</p><pre>// commonMain/data/local/DatabaseDriverFactory.kt<br>import app.cash.sqldelight.db.SqlDriver<br><br>expect class DatabaseDriverFactory {<br>    fun createDriver(): SqlDriver<br>}</pre><pre>// androidMain/data/local/DatabaseDriverFactory.android.kt<br>import android.content.Context<br>import app.cash.sqldelight.driver.android.AndroidSqliteDriver<br>import com.yourapp.db.AppDatabase<br><br>actual class DatabaseDriverFactory(private val context: Context) {<br>    actual fun createDriver(): SqlDriver =<br>        AndroidSqliteDriver(AppDatabase.Schema, context, &quot;weather.db&quot;)<br>}</pre><pre>// iosMain/data/local/DatabaseDriverFactory.ios.kt<br>import app.cash.sqldelight.driver.native.NativeSqliteDriver<br>import com.yourapp.db.AppDatabase<br><br>actual class DatabaseDriverFactory {<br>    actual fun createDriver(): SqlDriver =<br>        NativeSqliteDriver(AppDatabase.Schema, &quot;weather.db&quot;)<br>}</pre><h3>4.6 The Repository — Business Logic Core</h3><pre>// commonMain/domain/WeatherRepository.kt<br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.flow.flow<br>import kotlinx.datetime.Clock<br><br>sealed class Result&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : Result&lt;T&gt;()<br>    data class Error(val message: String, val cause: Throwable? = null) : Result&lt;Nothing&gt;()<br>    object Loading : Result&lt;Nothing&gt;()<br>}<br>data class WeatherDomain(<br>    val city: String,<br>    val temperatureCelsius: Double,<br>    val humidity: Int,<br>    val description: String,<br>    val isCached: Boolean = false<br>)<br>class WeatherRepository(<br>    private val api: WeatherApi,<br>    private val db: AppDatabase,<br>    private val apiKey: String,<br>    private val cacheDurationMs: Long = 10 * 60 * 1000L // 10 minutes<br>) {<br>    fun getWeather(city: String): Flow&lt;Result&lt;WeatherDomain&gt;&gt; = flow {<br>        emit(Result.Loading)<br>        // 1. Check local cache first<br>        val cached = db.weatherCacheQueries.getWeatherByCity(city).executeAsOneOrNull()<br>        val now = Clock.System.now().toEpochMilliseconds()<br>        if (cached != null &amp;&amp; (now - cached.cached_at) &lt; cacheDurationMs) {<br>            emit(Result.Success(cached.toDomain(isCached = true)))<br>        }<br>        // 2. Fetch fresh from network<br>        try {<br>            val remote = api.getWeather(city, apiKey)<br>            db.weatherCacheQueries.insertOrReplace(<br>                city = remote.city,<br>                temperature = remote.main.temperature,<br>                humidity = remote.main.humidity.toLong(),<br>                description = remote.conditions.firstOrNull()?.description ?: &quot;&quot;,<br>                cached_at = now<br>            )<br>            emit(Result.Success(remote.toDomain()))<br>        } catch (e: Exception) {<br>            if (cached != null) {<br>                // Serve stale cache if network fails<br>                emit(Result.Success(cached.toDomain(isCached = true)))<br>            } else {<br>                emit(Result.Error(&quot;Failed to load weather: ${e.message}&quot;, e))<br>            }<br>        }<br>    }<br>    private fun WeatherCache.toDomain(isCached: Boolean = false) = WeatherDomain(<br>        city = city,<br>        temperatureCelsius = temperature,<br>        humidity = humidity.toInt(),<br>        description = description,<br>        isCached = isCached<br>    )<br>    private fun WeatherResponse.toDomain() = WeatherDomain(<br>        city = city,<br>        temperatureCelsius = main.temperature,<br>        humidity = main.humidity,<br>        description = conditions.firstOrNull()?.description ?: &quot;&quot;<br>    )<br>}</pre><h3>Consuming the Shared Module</h3><h3>5.1 Android (Jetpack Compose)</h3><pre>// androidApp/WeatherViewModel.kt<br>class WeatherViewModel(<br>    private val repository: WeatherRepository<br>) : ViewModel() {<br>private val _state = MutableStateFlow&lt;Result&lt;WeatherDomain&gt;&gt;(Result.Loading)<br>    val state: StateFlow&lt;Result&lt;WeatherDomain&gt;&gt; = _state.asStateFlow()<br>    fun loadWeather(city: String) {<br>        viewModelScope.launch {<br>            repository.getWeather(city).collect { _state.value = it }<br>        }<br>    }<br>}<br>// androidApp/WeatherScreen.kt<br>@Composable<br>fun WeatherScreen(viewModel: WeatherViewModel = viewModel()) {<br>    val state by viewModel.state.collectAsStateWithLifecycle()<br>    when (val s = state) {<br>        is Result.Loading -&gt; CircularProgressIndicator()<br>        is Result.Error   -&gt; Text(&quot;Error: ${s.message}&quot;, color = MaterialTheme.colorScheme.error)<br>        is Result.Success -&gt; WeatherCard(s.data)<br>    }<br>}<br>@Composable<br>fun WeatherCard(weather: WeatherDomain) {<br>    Card(modifier = Modifier.fillMaxWidth().padding(16.dp)) {<br>        Column(modifier = Modifier.padding(16.dp)) {<br>            Text(weather.city, style = MaterialTheme.typography.headlineMedium)<br>            Text(&quot;${weather.temperatureCelsius}°C · ${weather.description}&quot;)<br>            Text(&quot;Humidity: ${weather.humidity}%&quot;)<br>            if (weather.isCached) {<br>                Text(&quot;(Cached)&quot;, style = MaterialTheme.typography.labelSmall)<br>            }<br>        }<br>    }<br>}</pre><h3>5.2 iOS (SwiftUI)</h3><p>Consuming Kotlin Flow from Swift requires a wrapper since Swift can&#39;t directly collect them. Use <a href="https://skie.touchlab.co/">SKIE</a> or write a wrapper manually:</p><pre>// iosApp/WeatherViewModel.swift<br>import Shared<br>import Combine<br><br>@MainActor<br>class WeatherViewModel: ObservableObject {<br>    @Published var state: WeatherState = .loading<br>    private let repository: WeatherRepository<br>    private var task: Task&lt;Void, Never&gt;?<br>    init(repository: WeatherRepository) {<br>        self.repository = repository<br>    }<br>    func loadWeather(city: String) {<br>        task?.cancel()<br>        task = Task {<br>            // Using SKIE&#39;s async sequence bridge<br>            for await result in repository.getWeather(city: city) {<br>                if let success = result as? ResultSuccess&lt;WeatherDomain&gt; {<br>                    state = .success(success.data)<br>                } else if let error = result as? ResultError {<br>                    state = .error(error.message)<br>                } else {<br>                    state = .loading<br>                }<br>            }<br>        }<br>    }<br>}<br>// iosApp/WeatherView.swift<br>struct WeatherView: View {<br>    @StateObject private var viewModel = WeatherViewModel(<br>        repository: /* inject from DI */<br>    )<br>    var body: some View {<br>        Group {<br>            switch viewModel.state {<br>            case .loading:<br>                ProgressView()<br>            case .error(let msg):<br>                Text(msg).foregroundColor(.red)<br>            case .success(let weather):<br>                WeatherCard(weather: weather)<br>            }<br>        }<br>        .onAppear { viewModel.loadWeather(city: &quot;London&quot;) }<br>    }<br>}<br>struct WeatherCard: View {<br>    let weather: WeatherDomain<br>    var body: some View {<br>        VStack(alignment: .leading, spacing: 8) {<br>            Text(weather.city).font(.title)<br>            Text(&quot;\(String(format: &quot;%.1f&quot;, weather.temperatureCelsius))°C · \(weather.description)&quot;)<br>            Text(&quot;Humidity: \(weather.humidity)%&quot;)<br>            if weather.isCached {<br>                Text(&quot;Cached&quot;).font(.caption).foregroundColor(.secondary)<br>            }<br>        }<br>        .padding()<br>        .background(Color(.systemBackground))<br>        .cornerRadius(12)<br>        .shadow(radius: 4)<br>    }<br>}</pre><h3>Testing the Shared Module</h3><p>One of KMP’s underrated strengths is that your business logic is testable in pure JVM — no emulator needed.</p><pre>// commonTest/domain/WeatherRepositoryTest.kt<br>import kotlinx.coroutines.test.runTest<br>import kotlinx.coroutines.flow.toList<br>import kotlin.test.Test<br>import kotlin.test.assertEquals<br>import kotlin.test.assertIs<br><br>class WeatherRepositoryTest {<br>    private val fakeApi = FakeWeatherApi()<br>    private val fakeDb  = FakeWeatherDatabase()<br>    private val repository = WeatherRepository(<br>        api = fakeApi,<br>        db = fakeDb,<br>        apiKey = &quot;test-key&quot;<br>    )<br>    @Test<br>    fun `emits loading then success on network hit`() = runTest {<br>        fakeApi.response = WeatherResponse(<br>            city = &quot;Cairo&quot;,<br>            main = MainWeather(temperature = 35.0, humidity = 20),<br>            conditions = listOf(WeatherCondition(&quot;sunny&quot;, &quot;01d&quot;))<br>        )<br>        val emissions = repository.getWeather(&quot;Cairo&quot;).toList()<br>        assertIs&lt;Result.Loading&gt;(emissions[0])<br>        assertIs&lt;Result.Success&lt;WeatherDomain&gt;&gt;(emissions[1])<br>        assertEquals(&quot;Cairo&quot;, (emissions[1] as Result.Success).data.city)<br>    }<br>    @Test<br>    fun `falls back to stale cache on network error`() = runTest {<br>        fakeDb.seedCache(&quot;Cairo&quot;, temperature = 33.0, cachedAt = 0L) // stale<br>        fakeApi.shouldThrow = true<br>        val emissions = repository.getWeather(&quot;Cairo&quot;).toList()<br>        val result = emissions.last()<br>        assertIs&lt;Result.Success&lt;WeatherDomain&gt;&gt;(result)<br>        assertEquals(true, (result as Result.Success).data.isCached)<br>    }<br>}</pre><p>Run these tests on the JVM with a single ./gradlew:shared:testDebugUnitTest. No device needed.</p><h3>Advanced Patterns</h3><h3>Dependency Injection with Koin</h3><pre>// commonMain/di/SharedModule.kt<br>import org.koin.dsl.module<br>val sharedModule = module {<br>    single { createHttpClient() }<br>    single { WeatherApi(get()) }<br>    single { WeatherRepository(api = get(), db = get(), apiKey = BuildKonfig.API_KEY) }<br>}<br>// Android: in Application.onCreate()<br>startKoin {<br>    modules(sharedModule + androidModule)<br>}<br>// iOS: in Swift AppDelegate / @main<br>// Use KoinKt.doInitKoin() generated by Koin annotations</pre><h3>BuildKonfig for Shared Constants</h3><p>Use the <a href="https://github.com/yshrsmz/BuildKonfig">BuildKonfig</a> plugin to inject build-time constants into commonMain:</p><pre>// shared/build.gradle.kts<br>buildkonfig {<br>    packageName = &quot;com.yourapp&quot;<br>    defaultConfigs {<br>        buildConfigField(STRING, &quot;API_KEY&quot;, System.getenv(&quot;WEATHER_API_KEY&quot;) ?: &quot;&quot;)<br>        buildConfigField(STRING, &quot;BASE_URL&quot;, &quot;https://api.openweathermap.org&quot;)<br>    }<br>}</pre><h3>Conclusion</h3><p>KMP is not trying to replace native development — it’s trying to eliminate the worst part of it: writing the same business logic twice. When you strip away UI concerns, a huge portion of an app’s complexity lives in the shared layer: API calls, caching strategies, business rules, state management. KMP lets you solve those problems once, in Kotlin, and trust both platforms to render them beautifully.</p><p><strong>Choose KMP when:</strong></p><ul><li>You have experienced Android and iOS engineers</li><li>Platform fidelity is non-negotiable</li><li>You want progressive adoption (one module at a time)</li><li>Long-term maintenance cost matters more than short-term speed</li></ul><p><strong>The real promise of KMP</strong> isn’t just code reuse — it’s a single source of truth for your logic, which means fewer bugs, easier testing, and features that ship consistently across platforms at the same time.</p><p>The tooling is mature. The ecosystem is rich. The migration path is gradual. There’s never been a better time to start.</p><p><em>Happy to hear your KMP experiences — drop a comment below or reach out on Twitter/X.</em></p><p><strong>Tags:</strong> #KMP #KotlinMultiplatform #MobileDevelopment #Android #iOS #Kotlin</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada63a569597" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>