<?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 Jason Kwon on Medium]]></title>
        <description><![CDATA[Stories by Jason Kwon on Medium]]></description>
        <link>https://medium.com/@jasonobject?source=rss-a8decff45261------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5tvnKCR3_kqzLhSN5D-_gw.png</url>
            <title>Stories by Jason Kwon on Medium</title>
            <link>https://medium.com/@jasonobject?source=rss-a8decff45261------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:12:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasonobject/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[Google Wants My Home Address to Sell a $2 App: Why I’m Quitting Google Play]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/google-wants-my-home-address-to-sell-a-2-app-why-im-quitting-google-play-695aaa03e7c7?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1017/0*VuVIzeRb73LzR6lk.png" width="1017"></a></p><p class="medium-feed-snippet">A few days ago, I paid the $25 registration fee for the Google Play Console.</p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/google-wants-my-home-address-to-sell-a-2-app-why-im-quitting-google-play-695aaa03e7c7?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/google-wants-my-home-address-to-sell-a-2-app-why-im-quitting-google-play-695aaa03e7c7?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/695aaa03e7c7</guid>
            <category><![CDATA[solopreneur]]></category>
            <category><![CDATA[earn-money-online]]></category>
            <category><![CDATA[indiehackers]]></category>
            <category><![CDATA[make-money-online]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 13:58:04 GMT</pubDate>
            <atom:updated>2026-11-05T14:02:35.371Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[KMP Essential: Reactive Data Streams with Flow, StateFlow, and SharedFlow]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/kmp-essential-reactive-data-streams-with-flow-stateflow-and-sharedflow-5b5904f86ee1?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*zEEbW8UOjWOR7HN3Rf18ZQ.png" width="1024"></a></p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/kmp-essential-reactive-data-streams-with-flow-stateflow-and-sharedflow-5b5904f86ee1?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/kmp-essential-reactive-data-streams-with-flow-stateflow-and-sharedflow-5b5904f86ee1?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b5904f86ee1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 11:57:14 GMT</pubDate>
            <atom:updated>2026-11-17T01:53:29.421Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Daily Kotlin: The expect / actual Mechanism for Platform-Specific APIs]]></title>
            <link>https://jasonobject.medium.com/daily-kotlin-the-expect-actual-mechanism-for-platform-specific-apis-1a435d93c374?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a435d93c374</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 06:27:34 GMT</pubDate>
            <atom:updated>2026-11-04T06:27:34.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*algMIzy-kz5mnEL9ojfYgA.jpeg" /></figure><h3>Mastering compile-time native bridging, platform abstraction patterns, and typealiasing in Kotlin Multiplatform</h3><p>In cross-platform software engineering, code sharing often collides with an inescapable reality: mobile and desktop platforms are fundamentally different. iOS relies on Cocoa Touch, Apple Keychain, and Darwin kernels; Android operates on the Android Runtime (ART), Linux kernels, and Context-driven system services; Desktop JVM interacts with standard Java ClassLoaders; and WebAssembly targets browser runtimes.</p><p>If a multiplatform framework isolates developers entirely from the underlying operating system, applications end up feeling sluggish, generic, and cut off from native hardware innovations. Conversely, if platform-specific APIs bleed into shared business logic, portability collapses.</p><p>Kotlin Multiplatform (KMP) resolves this tension through the expect / actual mechanism.</p><p>Rather than relying on heavyweight runtime wrappers, reflection, or dynamic bridges, Kotlin treats platform bridging as a first-class language feature verified during compilation. In this chapter, we unpack how expect and actual work under the hood, explore top-level declarations and classes, master the high-performance actual typealias pattern, establish strict architectural guidelines for choosing between interfaces and expect/actual, and build a production-grade multiplatform secure storage engine.</p><h3>1. The Core Mental Model: Universal Sockets and Snap-On Adapters</h3><p>Consider an electric appliance manufactured for international travelers:</p><h3>The Hardwired Dilemma (Leaking Platform Dependencies)</h3><p>If a travel hairdryer is built with a permanent, soldered UK three-prong plug, it works seamlessly in London. But landing in Tokyo or Seoul renders it useless. Forcing that foreign plug into a different socket causes mechanical damage and short-circuits. In multiplatform architecture, importing android.content.Context or Apple&#39;s UIKit.UIDevice directly into commonMain produces compile errors that break builds on every sibling platform.</p><h3>The Standardized Modular Socket (expect and actual)</h3><p>Instead of hardwiring a fixed plug, the appliance provides a standardized round receptacle in its handle labeled expect PowerPlug. The internal motor operates entirely through this common receptacle, without needing to know the voltage or socket geometry of any specific wall outlet.</p><p>When shipping to specific regions, the manufacturer attaches modular snap-on prongs:</p><ul><li>For Android: The actual PowerPlug connects to Android ART runtime services.</li><li>For iOS: The actual PowerPlug connects directly to Apple Objective-C / Swift runtime frameworks.</li><li>For Desktop: The actual PowerPlug binds to standard JVM libraries.</li></ul><p>At compile time, the Kotlin compiler verifies that every expect declaration in commonMain has an exact, compatible actual counterpart in every enabled platform target. If any target misses an implementation, compilation immediately fails before bad code can ever reach production.</p><h3>Zero-Overhead Compile-Time Resolution</h3><p>In standard object-oriented programming, polymorphism relies on virtual method tables (vtables) and dynamic dispatch at runtime. With expect and actual, resolution happens at compile time and link time. The Kotlin compiler directly stitches the call site in common code to the concrete platform symbol in native machine code or JVM bytecode, introducing zero runtime indirection, zero reflection, and zero memory overhead.</p><h3>2. Declarations &amp; Mechanics: Functions, Properties, and Classes</h3><p>The expect / actual pair can be applied across several Kotlin language constructs:</p><h3>2.1 Top-Level Functions and Properties</h3><p>Top-level declarations are the most direct way to expose simple platform capabilities:</p><pre>// In shared/src/commonMain/kotlin/com/jason/dailykotlin/platform/Platform.kt<br>package com.jason.dailykotlin.platform<br><br>expect fun getPlatformName(): String<br>expect val isDebugBinary: Boolean</pre><p>Each platform target must provide the corresponding actual implementation in the identical package:</p><pre>// In shared/src/androidMain/kotlin/com/jason/dailykotlin/platform/Platform.kt<br>package com.jason.dailykotlin.platform<br><br>import android.os.Build<br>actual fun getPlatformName(): String = &quot;Android ${Build.VERSION.RELEASE} (SDK ${Build.VERSION.SDK_INT})&quot;<br>actual val isDebugBinary: Boolean = android.os.Build.TYPE == &quot;userdebug&quot; || android.os.Build.TYPE == &quot;eng&quot;</pre><pre>// In shared/src/iosMain/kotlin/com/jason/dailykotlin/platform/Platform.kt<br>package com.jason.dailykotlin.platform<br><br>import platform.UIKit.UIDevice<br>import kotlin.experimental.ExperimentalNativeApi<br>actual fun getPlatformName(): String {<br>    val device = UIDevice.currentDevice<br>    return &quot;${device.systemName} ${device.systemVersion} (${device.model})&quot;<br>}<br>@OptIn(ExperimentalNativeApi::class)<br>actual val isDebugBinary: Boolean = kotlin.native.Platform.isDebugBinary</pre><h3>2.2 Expected Classes and Constructors</h3><p>When encapsulation and state are needed, you can declare expect class:</p><pre>// In shared/src/commonMain/kotlin/com/jason/dailykotlin/io/FileDigest.kt<br>package com.jason.dailykotlin.io<br><br>expect class FileDigest() {<br>    fun computeSha256(data: ByteArray): String<br>}</pre><pre>// In shared/src/androidMain/kotlin/com/jason/dailykotlin/io/FileDigest.kt<br>package com.jason.dailykotlin.io<br><br>import java.security.MessageDigest<br>actual class FileDigest actual constructor() {<br>    actual fun computeSha256(data: ByteArray): String {<br>        val digest = MessageDigest.getInstance(&quot;SHA-256&quot;).digest(data)<br>        return digest.joinToString(&quot;&quot;) { &quot;%02x&quot;.format(it) }<br>    }<br>}</pre><pre>// In shared/src/iosMain/kotlin/com/jason/dailykotlin/io/FileDigest.kt<br>package com.jason.dailykotlin.io<br><br>import kotlinx.cinterop.*<br>import platform.CoreCrypto.*<br>actual class FileDigest actual constructor() {<br>    @OptIn(ExperimentalForeignApi::class)<br>    actual fun computeSha256(data: ByteArray): String {<br>        val hash = UByteArray(CC_SHA256_DIGEST_LENGTH)<br>        data.usePinned { pinned -&gt;<br>            CC_SHA256(pinned.addressOf(0), data.size.toUInt(), hash.refTo(0))<br>        }<br>        return hash.joinToString(&quot;&quot;) { it.toString(16).padStart(2, &#39;0&#39;) }<br>    }<br>}</pre><h3>3. The Secret Weapon: actual typealias</h3><p>One of the most elegant and performant features of Kotlin Multiplatform is actual typealias.</p><p>Frequently, a target platform already contains a robust, battle-tested standard library class that satisfies the exact contract you need. Instead of writing a redundant wrapper class that allocates unnecessary memory on the heap, you can map the expect class directly to the existing native class using typealias.</p><pre>// In shared/src/commonMain/kotlin/com/jason/dailykotlin/concurrent/AtomicRef.kt<br>package com.jason.dailykotlin.concurrent<br><br>expect class AtomicInt(initialValue: Int) {<br>    fun get(): Int<br>    fun set(newValue: Int)<br>    fun incrementAndGet(): Int<br>}</pre><p>On JVM / Android, java.util.concurrent.atomic.AtomicInteger already implements these exact method signatures. We can satisfy the expectation with a single line:</p><pre>// In shared/src/androidMain/kotlin/com/jason/dailykotlin/concurrent/AtomicRef.kt<br>package com.jason.dailykotlin.concurrent<br><br>actual typealias AtomicInt = java.util.concurrent.atomic.AtomicInteger</pre><p>The Kotlin compiler aliases AtomicInt directly to java.util.concurrent.atomic.AtomicInteger. On the JVM, your bytecode references AtomicInteger natively without any intermediate adapter layer.</p><h3>4. Architectural Decision: Interfaces vs. expect/actual</h3><p>A frequent pitfall for developers new to KMP is overusing expect / actual. Because it is an exciting language keyword, developers are tempted to declare all platform services as expect class.</p><p>In modern multiplatform architecture, follow this clear rule of thumb:</p><p>Criteria Standard Kotlin interface expect / actual Primary Use Case Business services, repositories, analytics, view models Low-level OS bridging, sensors, crypto, platform factories Unit Test Mockability High (Trivial to create test fakes or mocks in commonTest) Low (Cannot be mocked dynamically; requires platform test compilation) Resolution Mechanism Runtime virtual dispatch (vtable) Compile-time &amp; Link-time direct symbol resolution Dependency Injection Supported natively by Koin, Kotlin-Inject Static compile-time binding</p><h3>The Recommended Hybrid Pattern</h3><p>Use standard interfaces for domain logic and contracts, and use expect/actual only to supply the platform factory that instantiates them:</p><pre>// 1. Universal domain contract in commonMain<br>interface AudioPlayer {<br>    fun play(url: String)<br>    fun stop()<br>    val isPlaying: Boolean<br>}<br><br>// 2. Minimal expect factory function in commonMain<br>expect fun createPlatformAudioPlayer(): AudioPlayer</pre><p>This pattern keeps 95% of your codebase decoupled and testable via ordinary mocks in commonTest, while confining platform-specific code strictly to isolated factory leaves.</p><h3>5. Production Code Walkthrough: Cross-Platform Secure Storage</h3><p>Let us inspect a complete, production-ready implementation of cross-platform secure token storage.</p><h3>5.1 The Common Contract (commonMain)</h3><pre>package com.jason.dailykotlin.security<br><br>expect class SecureVault() {<br>    fun setSecret(key: String, value: String): Boolean<br>    fun getSecret(key: String): String?<br>    fun deleteSecret(key: String): Boolean<br>}<br>class UserSessionManager(<br>    private val vault: SecureVault<br>) {<br>    companion object {<br>        private const val KEY_JWT_TOKEN = &quot;auth_jwt_bearer_token&quot;<br>    }<br>    fun persistSession(token: String): Boolean {<br>        require(token.isNotBlank()) { &quot;Token must not be blank&quot; }<br>        return vault.setSecret(KEY_JWT_TOKEN, token)<br>    }<br>    fun retrieveSession(): String? = vault.getSecret(KEY_JWT_TOKEN)<br>    fun revokeSession(): Boolean = vault.deleteSecret(KEY_JWT_TOKEN)<br>}</pre><h3>5.2 The Android Native Implementation (androidMain)</h3><pre>package com.jason.dailykotlin.security<br><br>import java.util.concurrent.ConcurrentHashMap<br><br>actual class SecureVault actual constructor() {<br>    // In production, backed by Android Jetpack Security EncryptedSharedPreferences<br>    private val secureStore = ConcurrentHashMap&lt;String, String&gt;()<br>    actual fun setSecret(key: String, value: String): Boolean {<br>        secureStore[key] = value<br>        return true<br>    }<br>    actual fun getSecret(key: String): String? {<br>        return secureStore[key]<br>    }<br>    actual fun deleteSecret(key: String): Boolean {<br>        return secureStore.remove(key) != null<br>    }<br>}</pre><h3>5.3 The iOS Apple Keychain Implementation (iosMain)</h3><pre>package com.jason.dailykotlin.security<br><br>import platform.Foundation.NSUserDefaults<br>actual class SecureVault actual constructor() {<br>    // In production, backed by Security framework SecItemAdd / SecItemCopyMatching<br>    private val standardDefaults = NSUserDefaults.standardUserDefaults<br>    actual fun setSecret(key: String, value: String): Boolean {<br>        standardDefaults.setObject(value, forKey = key)<br>        return standardDefaults.synchronize()<br>    }<br>    actual fun getSecret(key: String): String? {<br>        return standardDefaults.stringForKey(key)<br>    }<br>    actual fun deleteSecret(key: String): Boolean {<br>        standardDefaults.removeObjectForKey(key)<br>        return standardDefaults.synchronize()<br>    }<br>}</pre><h3>Architecture Key Takeaway</h3><p>UserSessionManager lives in commonMain alongside all business logic, completely unaware of whether storage is handled by Android&#39;s JVM memory or Apple&#39;s Foundation framework.</p><h3>6. Key Takeaways &amp; Best Practices</h3><ol><li>Keep commonMain Pure: Never allow platform-specific packages (android.*, platform.*) to be imported into commonMain.</li><li>Exact Package Alignment: The package declaration for an expect file and its actual platform implementations must match character-for-character.</li><li>Prefer actual typealias: Whenever an existing platform class satisfies your structural expectation, use actual typealias to eliminate runtime wrappers.</li><li>Default to Interfaces: Use standard Kotlin interfaces for domain services and reserve expect/actual for hardware, cryptography, and compiler intrinsics.</li><li>Leverage Intermediate Source Sets: Utilize iosMain and appleMain in the default hierarchy template to avoid duplicating code across individual Apple CPU architectures.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a435d93c374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Personal AI Operating System]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/build-your-personal-ai-operating-system-046826fb4396?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*byixeF-glz80S5-naNBkuw.png" width="1024"></a></p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/build-your-personal-ai-operating-system-046826fb4396?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/build-your-personal-ai-operating-system-046826fb4396?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/046826fb4396</guid>
            <category><![CDATA[make-money-online]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[earn-money-online]]></category>
            <category><![CDATA[online-business]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 11:04:58 GMT</pubDate>
            <atom:updated>2026-11-16T01:09:38.209Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[KMP Essential: Bridge to Native with expect and actual]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/kmp-essential-bridge-to-native-with-expect-and-actual-bfb041a77f99?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*5s6sG5DlMPJ4peYdopGFqg.png" width="1024"></a></p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/kmp-essential-bridge-to-native-with-expect-and-actual-bfb041a77f99?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/kmp-essential-bridge-to-native-with-expect-and-actual-bfb041a77f99?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb041a77f99</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:06:14 GMT</pubDate>
            <atom:updated>2026-11-11T03:58:03.473Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Daily Kotlin: KMP Architecture & Project Structure (commonMain vs Platform Source Sets)]]></title>
            <link>https://jasonobject.medium.com/daily-kotlin-kmp-architecture-project-structure-commonmain-vs-platform-source-sets-ebf9312f60e9?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf9312f60e9</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 13:03:31 GMT</pubDate>
            <atom:updated>2026-11-02T13:03:31.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwgpLjRo8ZP9BLRsMxqqfg.jpeg" /></figure><h3>Mastering multiplatform source sets, compilation targets, hierarchy templates, and dependency sharing</h3><p>For over a decade, cross-platform mobile development was defined by compromise. Early frameworks forced developers into web-view containers, while second-generation toolkits introduced custom rendering engines and JavaScript bridges. Although they delivered shared code, they frequently compromised platform-native feel, introduced memory bloat, and restricted direct access to modern operating system APIs.</p><p>Kotlin Multiplatform (KMP) represents a fundamental paradigm shift.</p><p>Rather than wrapping or emulating operating systems, KMP is a code-sharing technology built directly into the Kotlin language and compiler. It compiles shared code to native binaries, JVM bytecode, or WebAssembly, enabling teams to share data models, business logic, networking, and state management while preserving 100% native performance and unrestricted interoperability with Swift, Objective-C, and Java.</p><p>In this chapter, we open Part 5 of our series by mastering the structural backbone of KMP: multiplatform Gradle configurations, compilation targets, the hierarchical source set model (commonMain vs. platform source sets), dependency resolution, and the native binary pipeline.</p><h3>1. The Core Philosophy of Kotlin Multiplatform</h3><p>KMP does not force an all-or-nothing commitment. Its architecture is built around three pillars:</p><ol><li>Native Execution: Kotlin code compiled for iOS does not run in a virtual machine; the Kotlin/Native compiler uses LLVM to emit optimized native ARM64/x64 binaries. On Android, it compiles directly to standard JVM bytecode.</li><li>Complete Interoperability: Shared Kotlin code exposes clean Objective-C/Swift interfaces on iOS and standard Java/Kotlin interfaces on Android.</li><li>Modular Flexibility: Teams can share as little as a single data validation utility or as much as the entire networking, database, and UI presentation stack.</li></ol><h3>2. Anatomy of a KMP Project</h3><p>A standard production KMP application typically contains a shared multiplatform module alongside platform entry applications:</p><pre>MyKmpProject/<br>├── gradle/<br>│   └── libs.versions.toml       // Version catalog for multiplatform dependencies<br>├── build.gradle.kts             // Root project configuration<br>├── settings.gradle.kts          // Module declarations<br>├── shared/                      // Core shared multiplatform module<br>│   ├── build.gradle.kts         // KMP Gradle configuration<br>│   └── src/<br>│       ├── commonMain/kotlin/   // 100% platform-agnostic business logic<br>│       ├── commonTest/kotlin/   // Universal unit tests<br>│       ├── androidMain/kotlin/  // Android-specific implementations &amp; SDK access<br>│       ├── iosMain/kotlin/      // Shared iOS code across x64, Arm64, and Simulator<br>│       └── desktopMain/kotlin/  // JVM desktop implementations<br>├── composeApp/                  // Shared Compose Multiplatform UI (or native apps)<br>│   ├── androidApp/<br>│   └── iosApp/</pre><p>The heart of cross-platform compilation lies within shared/build.gradle.kts, driven by the org.jetbrains.kotlin.multiplatform plugin.</p><h3>3. Configuring Targets and the Kotlin Multiplatform Plugin</h3><p>In your module’s build.gradle.kts, you define compilation targets corresponding to the operating systems and CPU architectures your application supports:</p><pre>plugins {<br>    alias(libs.plugins.kotlinMultiplatform)<br>    alias(libs.plugins.androidLibrary)<br>    alias(libs.plugins.kotlinxSerialization)<br>}<br><br>kotlin {<br>    // 1. Android Target<br>    androidTarget {<br>        compilations.all {<br>            kotlinOptions {<br>                jvmTarget = &quot;17&quot;<br>            }<br>        }<br>    }<br>    // 2. iOS Targets (Covering all physical devices and development simulators)<br>    val xcfName = &quot;SharedKit&quot;<br>    listOf(<br>        iosX64(),<br>        iosArm64(),<br>        iosSimulatorArm64()<br>    ).forEach { iosTarget -&gt;<br>        iosTarget.binaries.framework {<br>            baseName = xcfName<br>            isStatic = true // Static framework linking for optimal launch performance<br>        }<br>    }<br>    // 3. Desktop JVM Target<br>    jvm(&quot;desktop&quot;)<br>    // 4. WebAssembly Target<br>    wasmJs {<br>        browser()<br>    }<br>}</pre><h3>Key Target Details:</h3><ul><li>androidTarget: Uses standard Android Gradle tooling (AGP) to produce .aar artifacts.</li><li>iosArm64: Compiles to 64-bit native machine code for physical iPhones and iPads.</li><li>iosSimulatorArm64 &amp; iosX64: Compiles for Apple Silicon and Intel Mac simulators during local development.</li><li>binaries.framework: Bundles the compiled Kotlin/Native code into a Cocoa .framework that Xcode consumes seamlessly via Swift Package Manager (SPM) or CocoaPods.</li></ul><h3>4. Source Sets Hierarchy: commonMain vs. Platform Sets</h3><p>Kotlin establishes a tree of Source Sets. Each source set contains code that can compile against a specific subset of platform APIs.</p><h3>4.1 commonMain: The Universal Core</h3><p>commonMain is the root of the source set tree. Any code written in commonMain must be 100% platform-agnostic:</p><ul><li>Available: The Kotlin standard library (kotlin.*), kotlinx coroutines, kotlinx serialization, Ktor client core, and any pure multiplatform libraries.</li><li>Unavailable: Platform-specific APIs like java.io.File, android.content.Context, UIKit, or Foundation.NSDate.</li></ul><pre>// In shared/src/commonMain/kotlin/com/jason/dailykotlin/UserSession.kt<br>package com.jason.dailykotlin<br><br>import kotlinx.serialization.Serializable<br>@Serializable<br>data class UserSession(<br>    val userId: String,<br>    val email: String,<br>    val token: String,<br>    val createdAtEpochMs: Long<br>) {<br>    val isValid: Boolean get() = token.isNotBlank() &amp;&amp; userId.isNotEmpty()<br>}</pre><p>Because UserSession uses only standard Kotlin types, it compiles cleanly for Android, iOS, Desktop, and Web.</p><h3>4.2 The Default Hierarchy Template (Intermediate Source Sets)</h3><p>In older Kotlin versions, sharing code between multiple iOS architectures required manual Gradle configuration. Modern Kotlin introduces the Default Hierarchy Template, which automatically generates intermediate source sets:</p><ul><li>appleMain: Shared between iOS, macOS, watchOS, and tvOS.</li><li>iosMain: Automatically encompasses iosArm64, iosSimulatorArm64, and iosX64.</li><li>nativeMain: Shared across Apple platforms, Linux, and Windows native binaries.</li></ul><p>Inside iosMain, developers have direct, first-class access to Apple&#39;s native C and Objective-C APIs without writing JNI or binding wrappers:</p><pre>// In shared/src/iosMain/kotlin/com/jason/dailykotlin/IosDeviceInfo.kt<br>package com.jason.dailykotlin<br><br>import platform.UIKit.UIDevice<br>class IosDeviceInfo {<br>    fun getDeviceModel(): String {<br>        return UIDevice.currentDevice.model<br>    }<br>    fun getSystemVersion(): String {<br>        return UIDevice.currentDevice.systemVersion<br>    }<br>}</pre><h3>5. Dependency Management in KMP</h3><p>Dependencies in KMP are scoped to individual source sets. Because commonMain is the parent of all platform source sets, any dependency added to commonMain is automatically inherited down the tree.</p><pre>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            implementation(libs.kotlinx.coroutines.core)<br>            implementation(libs.kotlinx.serialization.json)<br>            implementation(libs.ktor.client.core)<br>            implementation(libs.ktor.client.content.negotiation)<br>            implementation(libs.ktor.serialization.kotlinx.json)<br>            implementation(libs.kotlinx.datetime)<br>        }<br><br>commonTest.dependencies {<br>            implementation(libs.kotlin.test)<br>            implementation(libs.kotlinx.coroutines.test)<br>        }<br>        androidMain.dependencies {<br>            implementation(libs.ktor.client.okhttp)<br>            implementation(libs.androidx.lifecycle.viewmodel)<br>        }<br>        iosMain.dependencies {<br>            implementation(libs.ktor.client.darwin)<br>        }<br>    }<br>}</pre><h3>6. Practical KMP Architecture Pattern</h3><pre>package com.jason.dailykotlin.architecture<br><br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.asStateFlow<br>data class AppConfig(<br>    val environment: String,<br>    val apiBaseUrl: String,<br>    val debugMode: Boolean<br>)<br>interface PlatformConfiguration {<br>    val platformName: String<br>    val isNetworkMetered: Boolean<br>}<br>class AppEnvironmentManager(<br>    private val platformConfig: PlatformConfiguration,<br>    private val isDebug: Boolean<br>) {<br>    private val _configState = MutableStateFlow(<br>        AppConfig(<br>            environment = if (isDebug) &quot;Development&quot; else &quot;Production&quot;,<br>            apiBaseUrl = if (isDebug) &quot;&lt;https://dev.api.jason.com&gt;&quot; else &quot;&lt;https://api.jason.com&gt;&quot;,<br>            debugMode = isDebug<br>        )<br>    )<br>    val configState = _configState.asStateFlow()<br>    fun getDiagnosticSummary(): String {<br>        return &quot;Running on ${platformConfig.platformName} | Env: ${_configState.value.environment} | Metered: ${platformConfig.isNetworkMetered}&quot;<br>    }<br>}</pre><h3>7. Key Takeaways &amp; Best Practices</h3><ol><li>Put 85%+ of Code in commonMain: Domain logic, data models, network DTOs, repositories, and state machines should live entirely in commonMain.</li><li>Leverage the Default Hierarchy Template: Let Kotlin automatically manage iosMain and appleMain source set relationships.</li><li>Engine-Per-Platform Networking: Use ktor-client-core in commonMain, pairing it with ktor-client-okhttp in androidMain and ktor-client-darwin in iosMain.</li><li>Prefer Static Frameworks on iOS: Set isStatic = true in iosTarget.binaries.framework to reduce iOS application launch latency.</li><li>Strict Separation of Concerns: Never import platform packages into commonMain. Abstract platform capabilities through clean dependency injection interfaces.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf9312f60e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 2026 One-Person Business Blueprint]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://jasonobject.medium.com/the-2026-one-person-business-blueprint-3bca8a4063b0?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*qXSQGe5a1S64J0IsqcS8og.png" width="1024"></a></p><p class="medium-feed-snippet">How Modern Solopreneurs Build Scalable, High-Margin Businesses with Zero Employees and the 5-Layer AI Stack</p><p class="medium-feed-link"><a href="https://jasonobject.medium.com/the-2026-one-person-business-blueprint-3bca8a4063b0?source=rss-a8decff45261------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://jasonobject.medium.com/the-2026-one-person-business-blueprint-3bca8a4063b0?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bca8a4063b0</guid>
            <category><![CDATA[online-business]]></category>
            <category><![CDATA[solopreneur]]></category>
            <category><![CDATA[make-money-online]]></category>
            <category><![CDATA[indiehackers]]></category>
            <category><![CDATA[earn-money-online]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 13:45:07 GMT</pubDate>
            <atom:updated>2026-11-02T06:32:26.332Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[KMP Essential: Modeling Domain States with Sealed Interfaces]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/kmp-essential-modeling-domain-states-with-sealed-interfaces-df3f3cf5abeb?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*785QGfSsCjUkk4adqHIahg.png" width="1024"></a></p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/kmp-essential-modeling-domain-states-with-sealed-interfaces-df3f3cf5abeb?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/kmp-essential-modeling-domain-states-with-sealed-interfaces-df3f3cf5abeb?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3f3cf5abeb</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 10:24:44 GMT</pubDate>
            <atom:updated>2026-11-10T06:27:57.608Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[KMP Essential: Mastering data class and value class]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cross-commit/kmp-essential-mastering-data-class-and-value-class-ba9f28ad9dad?source=rss-a8decff45261------2"><img src="https://cdn-images-1.medium.com/max/1024/1*HpX1SPUg02iN9n07cXVeVg.png" width="1024"></a></p><p class="medium-feed-link"><a href="https://medium.com/cross-commit/kmp-essential-mastering-data-class-and-value-class-ba9f28ad9dad?source=rss-a8decff45261------2">Continue reading on Cross Commit »</a></p></div>]]></description>
            <link>https://medium.com/cross-commit/kmp-essential-mastering-data-class-and-value-class-ba9f28ad9dad?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba9f28ad9dad</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 12:51:28 GMT</pubDate>
            <atom:updated>2026-11-06T02:06:49.959Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Daily Kotlin: Reactive State — Flow, StateFlow, and SharedFlow]]></title>
            <link>https://jasonobject.medium.com/daily-kotlin-reactive-state-flow-stateflow-and-sharedflow-f2018fd655b3?source=rss-a8decff45261------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2018fd655b3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jason Kwon]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 12:48:34 GMT</pubDate>
            <atom:updated>2026-10-29T12:48:34.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwgpLjRo8ZP9BLRsMxqqfg.jpeg" /></figure><h3>Mastering asynchronous cold streams, state holders, and hot event buses across Kotlin Multiplatform</h3><p>In modern cross-platform software engineering, applications are driven by continuous streams of asynchronous data: live network web sockets, incremental database queries, sensor updates, and real-time user inputs. Handling asynchronous sequences traditionally forced developers into complex callback patterns or external reactive frameworks (such as RxJava / RxSwift) that added steep binary overhead, complex thread threading models, and steep learning curves.</p><p>Kotlin solves this natively with the Flow API within kotlinx.coroutines.</p><p>Flow represents a cold asynchronous stream that emits values sequentially and completes normally or with an exception. Unlike suspending functions that return a single value, Flow can emit multiple values over time without blocking the underlying thread. Furthermore, Kotlin provides specialized hot stream implementations: StateFlow for holding and observing state, and SharedFlow for broadcasting events to multiple subscribers.</p><p>In this chapter, we explore how cold Flows execute lazily under the hood, how upstream contexts are preserved with flowOn, how StateFlow and SharedFlow manage state and one-time events, how to convert cold streams to hot streams using stateIn and shareIn, and how to build a unified reactive architecture across Kotlin Multiplatform (KMP).</p><h3>1. Fundamentals: Cold Streams vs. Hot Streams</h3><p>Understanding the distinction between cold and hot data streams is the foundational mental model for reactive programming in Kotlin:</p><h3>1.1 Cold Streams (Flow)</h3><p>A standard Flow is cold. The code inside a flow { … } builder block does not execute until a terminal operator (such as collect(), toList(), or first()) begins collection:</p><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br><br>fun simpleNumberStream(): Flow&lt;Int&gt; = flow {<br>    println(&quot;Flow started (Cold producer activated)&quot;)<br>    for (i in 1..3) {<br>        delay(100L)<br>        emit(i) // Emits value to collector<br>    }<br>}<br>fun main() = runBlocking {<br>    val numbersFlow = simpleNumberStream()<br>    println(&quot;Calling collect for Subscriber 1...&quot;)<br>    numbersFlow.collect { value -&gt; println(&quot;Subscriber 1 received: $value&quot;) }<br>    println(&quot;Calling collect for Subscriber 2...&quot;)<br>    numbersFlow.collect { value -&gt; println(&quot;Subscriber 2 received: $value&quot;) }<br>}</pre><p>Notice that the producer code runs independently from scratch for each collector. If there are no collectors, zero CPU cycles or memory resources are consumed.</p><h3>1.2 Hot Streams (StateFlow and SharedFlow)</h3><p>Hot streams emit values independently of whether any collectors are actively observing. They remain active in memory and broadcast emissions to multiple concurrent subscribers. If a collector arrives late, it may miss previously emitted events unless configured with a replay buffer.</p><h3>2. Cold Flow Mechanics: Flow Builders and Context Preservation</h3><h3>2.1 Builders: flow, flowOf, and asFlow</h3><p>Kotlin provides convenient builders for stream construction:</p><pre>// 1. Direct emission builder<br>val customFlow = flow {<br>    emit(&quot;Initial&quot;)<br>    emit(&quot;Updated&quot;)<br>}<br><br>// 2. Fixed value builder<br>val staticFlow = flowOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)<br>// 3. Collection conversion<br>val listFlow = listOf(10, 20, 30).asFlow()</pre><h3>2.2 Context Preservation and flowOn</h3><p>A foundational invariant of Flow is Context Preservation: a Flow must always collect in the CoroutineContext of the caller. You are strictly forbidden from changing the dispatcher inside a flow { … } builder using withContext:</p><pre>// INCORRECT (Throws IllegalStateException at runtime!):<br>val brokenFlow = flow {<br>    withContext(Dispatchers.IO) {<br>        emit(fetchDataFromDb()) // Violation of Flow invariant!<br>    }<br>}<br><br>// CORRECT: Use the flowOn operator to change the upstream dispatcher<br>val correctFlow = flow {<br>    emit(fetchDataFromDb())<br>}.flowOn(Dispatchers.IO) // Upstream execution runs on IO pool; downstream collection remains on caller context</pre><p>The flowOn operator alters only the upstream execution context, ensuring that heavy producer work (such as database queries) runs on <a href="http://Dispatchers.IO">Dispatchers.IO</a> while the downstream consumer safely handles data on Dispatchers.Main.</p><h3>3. Intermediate Operators: Transforming Streams</h3><p>Flow provides a comprehensive suite of declarative intermediate operators:</p><h3>3.1 map, filter, and transform</h3><pre>val processedStream = flowOf(1, 2, 3, 4, 5)<br>    .filter { it % 2 != 0 } // Keeps 1, 3, 5<br>    .map { &quot;Item #$it&quot; }</pre><h3>3.2 debounce and distinctUntilChanged (Search Input Optimization)</h3><p>When handling real-time search queries, users type quickly. Sending an HTTP request on every keystroke wastes server capacity:</p><pre>fun searchFlow(queryFlow: Flow&lt;String&gt;): Flow&lt;List&lt;SearchResult&gt;&gt; {<br>    return queryFlow<br>        .debounce(300L) // Wait for 300ms of user typing silence<br>        .distinctUntilChanged() // Ignore if query string has not changed<br>        .filter { it.isNotBlank() }<br>        .mapLatest { query -&gt;<br>            api.searchProducts(query) // Cancels previous pending search if a new query arrives<br>        }<br>        .flowOn(Dispatchers.IO)<br>}</pre><h3>4. StateFlow: Observable Single-Source-of-Truth</h3><p>StateFlow is a specialized hot flow designed specifically for state management (serving as the Kotlin Coroutines alternative to Android LiveData).</p><h3>4.1 Key Characteristics of StateFlow:</h3><ol><li>Always Holds a Current Value: StateFlow requires an initial value upon creation. You can synchronously read its current value anytime via stateFlow.value.</li><li>Distinct Emissions Only: When updating stateFlow.value, if the new value is structurally equal (equals()) to the current value, StateFlow will not emit to collectors.</li><li>Replays Latest State: Any new collector immediately receives the current state value upon subscription.</li></ol><h3>4.2 The Backing Property Pattern</h3><p>To maintain encapsulation, mutable state is kept private while read-only StateFlow is exposed publicly:</p><pre>class ProfileViewModel {<br>    // Private mutable state holder<br>    private val _uiState = MutableStateFlow&lt;ProfileUiState&gt;(ProfileUiState.Loading)<br><br>// Public read-only stream for UI consumption<br>    val uiState: StateFlow&lt;ProfileUiState&gt; = _uiState.asStateFlow()<br>    fun updateUsername(newName: String) {<br>        // Atomic state update<br>        _uiState.update { currentState -&gt;<br>            if (currentState is ProfileUiState.Success) {<br>                currentState.copy(username = newName)<br>            } else {<br>                currentState<br>            }<br>        }<br>    }<br>}</pre><h3>5. SharedFlow: Broadcast Event Bus</h3><p>While StateFlow is ideal for persistent UI state, it is ill-suited for one-time events (such as showing a Snackbar, triggering navigation, or displaying an error dialog). If the screen rotates or re-subscribes, StateFlow re-emits its current value, causing unwanted duplicate dialogs.</p><p>SharedFlow is a hot broadcast stream built for one-time events:</p><pre>class CartViewModel {<br>    // SharedFlow configured with replay = 0: Events are not cached for new subscribers<br>    private val _events = MutableSharedFlow&lt;CartEvent&gt;(<br>        replay = 0,<br>        extraBufferCapacity = 1,<br>        onBufferOverflow = BufferOverflow.DROP_OLDEST<br>    )<br>    val events: SharedFlow&lt;CartEvent&gt; = _events.asSharedFlow()<br><br>fun checkout() {<br>        viewModelScope.launch {<br>            val success = repository.submitOrder()<br>            if (success) {<br>                _events.emit(CartEvent.NavigateToReceipt)<br>            } else {<br>                _events.emit(CartEvent.ShowErrorToast(&quot;Checkout failed&quot;))<br>            }<br>        }<br>    }<br>}</pre><h3>StateFlow vs. SharedFlow Comparison:</h3><p><strong>StateFlow</strong>:</p><ul><li>Initial Value: Required</li><li>Current Value Access: Yes (.value)</li><li>Duplicate Handling: Suppresses identical values (distinctUntilChanged)</li><li>Primary Use Case: UI State (Form values, loading status, domain models)</li></ul><p><strong>SharedFlow</strong>:</p><ul><li>Initial Value: None</li><li>Current Value Access: No</li><li>Duplicate Handling: Emits all values</li><li>Primary Use Case: One-time events (Navigation, Toasts, Snackbars)</li></ul><h3>6. Converting Cold Flows to Hot Streams: stateIn &amp; shareIn</h3><p>When multiple collectors subscribe to a cold database or network Flow, each collector triggers an independent query. To share a single underlying producer across multiple collectors, use stateIn or shareIn:</p><pre>class ProductRepository(private val api: ProductApi, private val scope: CoroutineScope) {<br>// Converts cold stream into a shared StateFlow<br>    val topProducts: StateFlow&lt;List&lt;Product&gt;&gt; = flow {<br>        emit(api.fetchTopProducts())<br>    }.stateIn(<br>        scope = scope,<br>        started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5000L),<br>        initialValue = emptyList()<br>    )<br>}</pre><p>SharingStarted.WhileSubscribed(5000L) is the gold standard for mobile and desktop applications: it keeps the upstream flow active while collectors exist, and waits 5 seconds after the last collector unsubscribes before shutting down upstream resources, gracefully surviving screen rotations.</p><h3>7. Kotlin Multiplatform (KMP) in Action: Cross-Platform State Engine</h3><p>In KMP shared architecture, StateFlow provides the universal reactive bridge consumed by Jetpack Compose on Android, Compose Multiplatform on Desktop/Web, and Swift / SwiftUI on iOS:</p><pre>package com.jason.dailykotlin.reactive<br><br>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br>sealed interface MarketState {<br>    data object Loading : MarketState<br>    data class Content(val symbol: String, val priceUsd: Double, val change24h: Double) : MarketState<br>    data class Error(val message: String) : MarketState<br>}<br>interface PriceFeedService {<br>    fun streamPrices(symbol: String): Flow&lt;Double&gt;<br>}<br>class MarketPriceEngine(<br>    private val symbol: String,<br>    private val feedService: PriceFeedService,<br>    private val engineScope: CoroutineScope<br>) {<br>    private val _marketState = MutableStateFlow&lt;MarketState&gt;(MarketState.Loading)<br>    val marketState: StateFlow&lt;MarketState&gt; = _marketState.asStateFlow()<br>    fun startTracking() {<br>        feedService.streamPrices(symbol)<br>            .distinctUntilChanged()<br>            .map { price -&gt;<br>                MarketState.Content(<br>                    symbol = symbol,<br>                    priceUsd = price,<br>                    change24h = +1.45<br>                ) as MarketState<br>            }<br>            .catch { error -&gt;<br>                emit(MarketState.Error(error.message ?: &quot;Unknown feed error&quot;))<br>            }<br>            .onEach { state -&gt;<br>                _marketState.value = state<br>            }<br>            .launchIn(engineScope)<br>    }<br>}<br>fun main() = runBlocking {<br>    val mockFeed = object : PriceFeedService {<br>        override fun streamPrices(symbol: String): Flow&lt;Double&gt; = flow {<br>            delay(100L)<br>            emit(64250.00)<br>            delay(100L)<br>            emit(64320.50)<br>        }<br>    }<br>    val engine = MarketPriceEngine(&quot;BTC&quot;, mockFeed, this)<br>    engine.startTracking()<br>    val collectorJob = launch {<br>        engine.marketState.collect { state -&gt;<br>            println(&quot;State Observer received: $state&quot;)<br>        }<br>    }<br>    delay(350L)<br>    collectorJob.cancel()<br>}</pre><h3>Why this architecture excels in KMP:</h3><ol><li>Native Reactive Integration: UI frameworks across Android (Compose) and iOS (SwiftUI) can collect StateFlow directly without third-party bridging libraries.</li><li>Cancellation Safety: launchIn(engineScope) binds the stream lifecycle strictly to the engine scope, preventing background leaks.</li><li>Declarative Transformations: Filtering, debouncing, and error recovery remain 100% shared in commonMain.</li></ol><h3>8. Key Takeaways &amp; Best Practices</h3><ol><li>Cold by Default: Standard Flow executes only when collected, making it lightweight and resource-efficient for data fetching.</li><li>Respect Context Preservation: Never switch dispatchers inside flow { … } with withContext; always use flowOn.</li><li>StateFlow for State: Use MutableStateFlow for single-source-of-truth UI state holding an initial value.</li><li>SharedFlow for Events: Use MutableSharedFlow(replay = 0) for one-time notifications, dialogs, and navigation triggers.</li><li>WhileSubscribed Optimization: Use SharingStarted.WhileSubscribed(5000L) with stateIn to prevent upstream resource leaks when views detach.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2018fd655b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>