<?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 Ofek Amirav on Medium]]></title>
        <description><![CDATA[Stories by Ofek Amirav on Medium]]></description>
        <link>https://medium.com/@ofek.amirav?source=rss-1e6bb850f692------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yRha8HNmN5jRZtVn</url>
            <title>Stories by Ofek Amirav on Medium</title>
            <link>https://medium.com/@ofek.amirav?source=rss-1e6bb850f692------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:51:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ofek.amirav/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[Tiered Data Fetching: How I Reduced API Calls by ~80% Without Sacrificing Freshness]]></title>
            <link>https://medium.com/@ofek.amirav/tiered-data-fetching-how-i-reduced-api-calls-by-80-without-sacrificing-freshness-9e47f55e8161?source=rss-1e6bb850f692------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e47f55e8161</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[data-fetching]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ofek Amirav]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 14:19:19 GMT</pubDate>
            <atom:updated>2026-03-09T14:19:19.703Z</atom:updated>
            <content:encoded><![CDATA[<p>A cache strategy built around how data actually changes - not how often users open screens.</p><p>The naive approach to fetching data is simple: the user opens a screen, you fetch the latest data. Every single time. It works. But it’s also incredibly wasteful in ways that compound quickly once you think about the actual nature of the data you’re fetching.</p><p>In QuiverSync, the core data is surf forecasts: wave height, period, wind speed, and swell direction for a given GPS location. This data comes from an external API (StormGlass), and it has a real cost per call.</p><p>More importantly, it changes on a predictable schedule. A forecast generated at 6 AM today is still highly accurate at 11 AM. However, yesterday’s forecast for a location I visited is completely worthless tomorrow morning. The data has a natural Time-To-Live (TTL), and that TTL varies depending on <em>how</em> the user is accessing it.</p><p>I built a three-tier fetch strategy around this exact observation.</p><h3>The Key Constants</h3><p>Every decision in the fetch logic flows from two main numbers:</p><pre>private val DAYS_TO_FETCH_FROM_API = 14<br>private val MIN_DAYS_REQUIRED_IN_DB = 8</pre><p><strong>14 days</strong> is what we request from the API in a single network call. <strong>8 days</strong> is the minimum we need locally before we consider the cache “sufficient”.</p><p>The gap between them is intentional: a 14-day fetch means we won’t need another API call for at least 6 days, even accounting for daily entries expiring.</p><h3>Tier 1: Home Screen (Location-Aware Caching)</h3><p>The home screen shows today’s forecast for the user’s current location. It runs the most frequently, so it requires the most aggressive caching strategy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f19ac988b789ce55d46e0ce3d75094/href">https://medium.com/media/43f19ac988b789ce55d46e0ce3d75094/href</a></iframe><p>The <strong>7km radius</strong> handles an important real-world case: GPS coordinates vary slightly between sessions. Without this, standing on the same beach but getting slightly different GPS readings would generate separate cache entries and unnecessary API calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/576f81dec37105bcc739a00dde322677/href">https://medium.com/media/576f81dec37105bcc739a00dde322677/href</a></iframe><p>The home page logic answers one simple question: <em>“Has anything meaningful changed since we last fetched?”</em> If the answer is no (same day, same location, enough data) the user gets a response directly from SQLDelight with <strong>zero network activity</strong>.</p><h3>Tier 2: Spot Detail Screen (Full 14-Day Fetch)</h3><p>When a user taps into a specific spot’s detail page, they expect the full forecast range. This is where we fetch 14 days if we don’t have them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f223cfd638985f44ec7df915f47cd7/href">https://medium.com/media/30f223cfd638985f44ec7df915f47cd7/href</a></iframe><blockquote><strong><em>Architectural Note:</em></strong><em> The Gemini prediction invalidation here is a crucial coupling decision. Forecasts and AI recommendations share a lifecycle. Doing this at the Repository level - rather than in a ViewModel or UseCase, ensures this invariant is enforced everywhere automatically.</em></blockquote><h3>Tier 3: Favorite Spots (Today-Only Fetch)</h3><p>The favorite spots list shows a single day’s forecast for each saved location. There’s no reason to fetch 14 days for every spot on the list, only today matters here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e75eeca6ec59ae83be36184e56525386/href">https://medium.com/media/e75eeca6ec59ae83be36184e56525386/href</a></iframe><p>This is the most targeted tier: one entry per spot, one API call <em>only</em> if that specific entry is missing. A user with 5 favorite spots who opens the app on a new day generates at most 5 API call and zero on subsequent opens the same day.</p><h3>The Decision Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_O-frTURZWynsQL_j8RWA.png" /></figure><h3>What This Gets Right</h3><p><strong>1. Cache invalidation is data-driven, not time-driven.</strong> The cache isn’t invalidated after an arbitrary <em>X</em> minutes, it’s invalidated when the oldest entry is no longer today’s date, or when the user has genuinely moved to a different location. This maps directly to how weather forecast data actually expires.</p><p><strong>2. API failures degrade gracefully.</strong> Every fetch path returns cached data if the API call fails. The user sees slightly stale data rather than a glaring error screen. For a forecast app, slightly stale data is almost always preferable to a blank screen.</p><p><strong>3. Prediction invalidation is automatic.</strong> When a new forecast is fetched, stale Gemini AI predictions for that spot are deleted at the repository level. This is enforced as a systemic invariant, not left to callers or ViewModels to remember.</p><p><strong>4. The home page never blocks on the network.</strong> On a typical day, the home screen returns data from SQLDelight in under 5ms. The API call only happens once per day, when the user first opens the app.</p><p>Surf conditions are dynamic but API budgets aren’t. The trick is building a cache that respects both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e47f55e8161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Offline-First Bidirectional Sync in Kotlin Multiplatform]]></title>
            <link>https://medium.com/@ofek.amirav/building-offline-first-bidirectional-sync-in-kotlin-multiplatform-8854a04e2e04?source=rss-1e6bb850f692------2</link>
            <guid isPermaLink="false">https://medium.com/p/8854a04e2e04</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[sqldelight]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Ofek Amirav]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 12:52:14 GMT</pubDate>
            <atom:updated>2026-03-09T12:52:14.494Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How I built a sync engine that makes network failures invisible to the user</strong></p><p>The internet is full of tutorials on how to fetch data from an API and display it in a UI. But very few show you what happens when the network suddenly vanishes mid-operation and what an app that handles that gracefully actually looks like under the hood.</p><p>In QuiverSync, a peer-to-peer surfboard rental app, two users interact with the same booking simultaneously: one renting, one owning. When one side takes an action accepts, cancels, requests an extension, the other side needs to see it immediately. And if either user’s network drops at the wrong moment, nothing should be lost.</p><p>Here’s the sync architecture I built to make that work.</p><h3>The Core Design Decision: Server Is Always Right</h3><p>Before writing any code, I made one rule explicit: <strong>Server is the source of truth. Always.</strong></p><p>This sounds obvious, but it has specific implications for conflict resolution. When a remote booking comes in with the same ID as a local one, the question isn’t “which is correct?”, it’s “which is newer?”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b227dc46ed2712466a50dece92663a7d/href">https://medium.com/media/b227dc46ed2712466a50dece92663a7d/href</a></iframe><p>This function is the entire conflict resolution logic. It lives in its own file, has no dependencies, and is trivially testable. Every sync decision flows through it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErqoqXQB4Mfr6gmrRbB2YA.png" /></figure><h3>The Architecture: Two Independent Jobs</h3><p>BookingSyncManager runs two concurrent jobs from the moment the user logs in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d31694b22e1c96701d8fa7d4879acc/href">https://medium.com/media/f0d31694b22e1c96701d8fa7d4879acc/href</a></iframe><p>The start() implementation guards against double-starts and reads the current user from SessionManager — no userId is passed in, keeping the call site clean.</p><h4>Job 1: Remote → Local</h4><p>The remote listener collects a Flow&lt;List&lt;Booking&gt;&gt; from Firestore and processes each incoming snapshot:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b439043cfdba825d45b50ba1c7c1c0a/href">https://medium.com/media/4b439043cfdba825d45b50ba1c7c1c0a/href</a></iframe><p>The SyncState.SYNCED guard is critical. e never delete a PENDING booking just because the server hasn&#39;t seen it yet.</p><h4>Job 2: Local PENDING → Remote</h4><p>The uploader observes a Flow of pending bookings from SQLDelight. It’s event-driven — it only wakes up when there’s something to sync:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc14fb58d6facbea3f15b2f0849c614/href">https://medium.com/media/3fc14fb58d6facbea3f15b2f0849c614/href</a></iframe><p>The retry mechanism is implicit: if a sync fails, the booking stays PENDING in SQLDelight. The next time the Flow emits (triggered by any DB change), the uploader tries again.</p><h3>What Made This Design Work</h3><p><strong>1. </strong><strong>shouldOverwriteLocalWithRemote as a pure function.</strong> Pulling conflict resolution into its own file meant I could write unit tests for every edge case (null existing, same timestamp, older remote) without spinning up a database or mocking Firestore. This is where the most dangerous bugs would hide.</p><p><strong>2. </strong><strong>SyncState enum as the source of pending truth.</strong> SQLDelight tracks SyncState.PENDING vs SyncState.SYNCED per row. This is the only thing the uploader needs to know. No in-memory queues, no separate pending table.</p><p><strong>3. Event-driven uploader, not polling.</strong> observePendingSync() returns a Flow, the uploader only runs when there are pending items. No battery drain from periodic checks, no delay from polling intervals.</p><p><strong>4. </strong><strong>applicationScope, not </strong><strong>viewModelScope.</strong> The sync manager lives for the user&#39;s session, not a single screen. Scoping it to the application&#39;s coroutine scope means it survives screen rotations, navigation, and the app going to background.</p><p><strong>5. Idempotent upsert.</strong> Both directions write through upsertBooking. Running the same operation twice produces the same result. This matters when Firestore re-delivers a snapshot or the network flickers.</p><p><strong>6. Preventing Infinite Sync Loops.</strong> By strictly comparing updatedAt and updating the local row to SYNCED only when the remote upsert succeeds, we break the echo chamber. When the server echoes the same booking back down to the local listener, shouldOverwriteLocalWithRemote evaluates safely, and the idempotent upsert simply updates the timestamp without triggering a new pending upload.</p><h3>The User Experience</h3><p>The user never sees a spinner for sync operations. They never see a “changes saved locally” banner. They never lose an action they took while offline.</p><p>The network failing is an implementation detail - not something the product should ever surface.</p><p><em>Questions about the sync architecture or edge cases I haven’t covered? Happy to discuss in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8854a04e2e04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Don’t Let Gemini Do All the Work]]></title>
            <link>https://medium.com/@ofek.amirav/why-i-dont-let-gemini-do-all-the-work-73b6c8ef7aed?source=rss-1e6bb850f692------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b6c8ef7aed</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ofek Amirav]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 22:52:25 GMT</pubDate>
            <atom:updated>2026-03-05T22:52:25.694Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Building a hybrid Rules + AI scoring system and why I’m already building its replacement</strong></p><p>When you’re building an AI-powered feature, the first instinct is simple: send the data to the model, get an answer back, show it to the user.</p><p>It works. But it doesn’t scale and it doesn’t get smarter over time.</p><p>For a surfboard rental marketplace I’m building, I had three competing requirements: fast, cost-efficient, and accurate. I quickly realized those three goals are in direct tension if you rely on an LLM for every single request.</p><p>Here’s the architecture I ended up with, and the thinking behind each decision.</p><h3>The Problem With Pure AI Recommendations</h3><p>A naive implementation calls the model on every trigger: user opens the screen, data loads, request goes out, response comes back. Repeat for every user, every session, every condition change.</p><p>The issues compound fast:</p><ul><li><strong>Latency: </strong>every recommendation has a minimum 800ms ceiling, regardless of how simple the match is</li><li><strong>Cost: </strong>you’re paying for tokens on cases the model gets right every single time anyway</li><li><strong>Quality: </strong>sending a full data dump to an LLM is actually worse than sending a focused prompt. More context isn’t always better; irrelevant context dilutes the answer</li><li><strong>No feedback loop: </strong>responses disappear into the UI and teach you nothing</li></ul><p>The insight that changed my approach: most recommendations aren’t hard. A beginner surfer with a 2ft wave forecast doesn’t need Gemini to figure out the right board. The interesting cases, the ones where context genuinely matters are a minority.</p><p>So I stopped treating AI as the pipeline and started treating it as the exception handler.</p><h3>The Architecture: Three Stages</h3><h3>1. Rules-Based Pre-Scoring</h3><p>Before any API call happens, a local scoring engine evaluates every candidate board against the current conditions and the surfer’s profile.</p><p>The scoring is weighted across several parameters, things like the relationship between wave conditions and board characteristics, and how well the surfer’s profile aligns with each option. Each parameter contributes a weighted score. The result is a normalized confidence value between 0 and 1.</p><p>This runs entirely on-device. No network, no latency, no cost.</p><p><strong>Input:</strong></p><ul><li>Surfer profile (skill level, physical attributes, experience)</li><li>Real-time forecast data (wave conditions, wind, period)</li><li>Available board inventory</li></ul><p><strong>Output:</strong></p><ul><li>Ranked list of candidates</li><li>Confidence score per candidate (0.0 → 1.0)</li><li>Top candidate with score</li></ul><p>The key design decision: the scoring rules are explicit and deterministic. You can read them, debug them, and reason about why a specific board got a specific score. That transparency is valuable both for development and for what comes later.</p><h3>2. The Confidence Gate</h3><p>After pre-scoring, the top candidate’s score is compared against a threshold.</p><pre>if (topScore &gt;= CONFIDENCE_THRESHOLD) {<br>    → return cached or pre-scored result directly<br>    → no API call<br>} else {<br>    → escalate to Gemini with focused prompt<br>}</pre><p>The threshold isn’t arbitrary, it represents the point at which the rules engine is confident enough that adding AI is unlikely to change the outcome meaningfully. Tuning this threshold is one of the levers for balancing cost vs. accuracy.</p><p>In practice, roughly 70% of requests resolve at this stage. The rules engine handles the clear-cut cases; Gemini handles the edge cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yh8bEUhxN0v8skXrdV_xyw.png" /></figure><h3>3. Targeted Gemini Refinement</h3><p>When a request escalates to Gemini, the prompt is deliberately narrow. Instead of sending the full surfer profile, all available boards, and complete forecast data, the prompt contains:</p><ul><li>The top 3 pre-scored candidates (already ranked)</li><li>The specific parameters where the scoring was ambiguous</li><li>The surfer’s relevant context for those parameters only</li></ul><p>This focused approach does two things: it reduces token usage significantly, and it actually produces better answers. The model isn’t being asked to evaluate everything from scratch, it’s being asked to resolve a specific ambiguity, which is a task it handles well.</p><h3>The Part Most Articles Skip: Storing the Results</h3><p>Every recommendation that the model produces gets written to the local database before it’s returned to the UI.</p><p>This isn’t just caching (though it serves that purpose too). It’s data collection.</p><p>Every stored record contains:</p><ul><li>The input state at recommendation time (conditions, profile snapshot)</li><li>The pre-scoring results (all candidate scores)</li><li>The model’s output and the reasoning it provided</li><li>Whether the user acted on the recommendation</li></ul><p>Over time, this dataset becomes genuinely valuable. The current system uses Gemini because there isn’t enough labeled data to train a real model. But every session where the app runs is generating structured training examples inputs, reasoning, and implicit feedback signals.</p><p>The long-term path is clear: once the dataset is large enough, a lightweight on-device model replaces the Gemini call entirely for the common cases. The rules engine and the confidence gate remain. The expensive API call disappears.</p><p>Building with that future in mind from day one means the architecture doesn’t need to change, just the component that sits behind the gate.</p><h3>What This Pattern Is Really About</h3><p>The hybrid Rules + AI approach gets discussed mostly as a cost optimization. And yes, reducing API calls by ~70% matters. But I think the more interesting angle is what it says about how to build AI features responsibly.</p><p>A pure LLM pipeline is a black box that you’re dependent on forever. You can’t inspect why it made a specific recommendation, you can’t tune it without changing the prompt, and you’re never building toward anything more capable.</p><p>A rules engine with an AI escalation layer is different:</p><ul><li>The rules are readable and debuggable</li><li>The AI handles genuine ambiguity, not routine cases</li><li>The stored outputs are building a dataset</li><li>The architecture has a clear upgrade path</li></ul><p>This is especially relevant for a domain like surf conditions, where the rules aren’t arbitrary, they’re grounded in real physical relationships between wave characteristics, board design, and surfer capability. That domain knowledge belongs in code, not in a prompt.</p><h3>A Final Side Note</h3><p>For anyone building AI features in mobile apps , the pattern above isn’t specific to board recommendations. The same structure applies to any context where:</p><ul><li>You have deterministic rules that cover most cases</li><li>You have a small percentage of genuinely ambiguous cases</li><li>You want to collect data to improve the system over time</li></ul><p>The threshold value and the scoring parameters will differ. The architecture stays the same.</p><p>The architecture above is live and collecting data. The next post will cover what happens when the dataset is large enough to close the loop.</p><p><em>Building something similar or have a different approach to AI cost efficiency in mobile? Would love to hear about it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b6c8ef7aed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Solved the Biggest Architectural Trap in Kotlin Multiplatform (KMP)]]></title>
            <link>https://medium.com/@ofek.amirav/how-i-solved-the-biggest-architectural-trap-in-kotlin-multiplatform-kmp-93e19b078337?source=rss-1e6bb850f692------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e19b078337</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ofek Amirav]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 11:49:44 GMT</pubDate>
            <atom:updated>2026-03-05T11:49:44.724Z</atom:updated>
            <content:encoded><![CDATA[<h3>I didn’t write two ViewModels. I wrote one shared base and let each platform wrap it natively.</h3><p>Kotlin Multiplatform is an incredible tool. When I started building <strong>QuiverSync, </strong>a peer-to-peer surfboard rental app with real-time surf forecasting, AI-powered board matching, and live rental management. The promise of “write business logic once, run everywhere” was exactly what I needed.</p><p>I was a solo developer targeting Android and IOS simultaneously. KMP felt like the perfect lever.</p><p>But very quickly, I fell into the most common architectural trap in KMP: <strong>over-sharing</strong>.</p><h3>The Trap: Exposing StateFlow Directly to IOS</h3><p>In an attempt to maximize shared code, it’s tempting to place your entire Presentation layer inside commonMain and expose a StateFlow directly to Swift.</p><p>But IOS doesn’t speak StateFlow natively.</p><p>When you expose Kotlin Flows directly to Swift, you end up writing ugly workarounds in your SwiftUI views, manually starting and cancelling coroutine scopes, handling lifecycle events, mapping Kotlin types to Swift types. All inside what’s supposed to be a clean UI layer.</p><p>swift</p><pre>// ❌ THE BAD WAY - SwiftUI tangled with raw Kotlin internals<br>struct BadRentalScreen: View {<br>    @State private var uiState: RentalState = RentalState.Loading()<br>    let viewModel: SharedViewModel<br><br>    var body: some View {<br>        VStack { /* UI */ }<br>        .onAppear {<br>            // Manually collecting a Kotlin Flow - lifecycle is now your problem<br>            viewModel.uiState.collect(collector: { state in<br>                self.uiState = state<br>            }) { error in }<br>        }<br>    }<br>}</pre><p>In QuiverSync, I hit this hard on the rental booking flow: the screen would freeze mid-transition because the coroutine scope wasn’t being cancelled correctly on onDisappear. I spent days debugging what looked like a UI bug it was an architectural one.</p><h3>The Solution: Two Layers, Each Doing One Job</h3><p>After restructuring, my architecture has two clear layers:</p><p><strong>Layer 1: </strong><strong>expect/</strong><strong>actual BaseViewModel:</strong> handles coroutine scope lifecycle per platform.</p><p><strong>Layer 2 : Swift Wrapper:</strong> bridges the Kotlin ViewModel’s StateFlow to SwiftUI&#39;s state system using SKIE.</p><p>Each layer does exactly one job and nothing more.</p><h3>Layer 1: expect/actual BaseViewModel</h3><h3>The shared contract - commonMain</h3><p>kotlin</p><pre>// commonMain - every ViewModel in the app builds on this<br>package org.example.quiversync.features<br><br>import kotlinx.coroutines.CoroutineScope<br>import org.koin.core.component.KoinComponent<br><br>expect open class BaseViewModel() : KoinComponent {<br>    val scope: CoroutineScope<br>}</pre><p>This is the only ViewModel definition the shared module needs. It exposes a CoroutineScope and is a KoinComponentso any subclass can inject dependencies directly via by inject(), without constructor parameters.</p><h3>Android actual - BaseViewModel.android.kt</h3><p>kotlin</p><pre>// androidMain — inherits from ViewModel, gets viewModelScope for free<br>actual open class BaseViewModel : ViewModel(), KoinComponent {<br>    actual val scope: CoroutineScope = viewModelScope<br>}</pre><p>On Android, actual BaseViewModel extends androidx.lifecycle.ViewModel. The scope is viewModelScope lifecycle awareness, coroutine cancellation on onCleared(), all handled automatically by the framework. Zero extra code.</p><h3>iOS actual - BaseViewModel.ios.kt</h3><p>kotlin</p><pre>// iosMain — no ViewModel base class on iOS, so we manage scope manually<br>actual open class BaseViewModel : KoinComponent {<br>    actual val scope: CoroutineScope = CoroutineScope(Dispatchers.IO)<br><br>    fun clear() {<br>        scope.cancel()<br>    }<br>}</pre><p>On iOS there’s no ViewModel to inherit from, so the actual manages its own scope. The clear() function must be called from SwiftUI when the screen disappears that&#39;s the one manual contract iOS requires.</p><h3>A Real ViewModel: UserViewModel</h3><p>Here’s what a real ViewModel looks like using this base. The UserViewModel loads a user profile, then in parallel observes their board count, spot count, and rental count, combining three live streams into one UI state:</p><p>kotlin</p><pre>// commonMain — works identically on Android and iOS<br>class UserViewModel(<br>    private val userUseCases: UserUseCases<br>) : BaseViewModel() {</pre><pre>private val _uiState = MutableStateFlow&lt;UserState(UserState.Loading)<br>    val uiState: StateFlow&lt;UserState&gt; get() = _uiState<br>    init {<br>        observeUserProfile()<br>    }<br>    @OptIn(ExperimentalCoroutinesApi::class)<br>    private fun observeUserProfile() {<br>        scope.launch {<br>            userUseCases.getUserProfileUseCase()<br>                .distinctUntilChanged()<br>                .flatMapLatest { userResult -&gt;<br>                    when (userResult) {<br>                        is Result.Success -&gt; {<br>                            val user = userResult.data<br>                            if (user != null) {<br>                                // Three Firestore streams combined in real-time<br>                                combine(<br>                                    userUseCases.getBoardsNumberUseCase.observe(user.uid),<br>                                    userUseCases.getSpotsNumberUseCase.observe(user.uid),<br>                                    userUseCases.getRentalsNumberUseCase.observe(user.uid)<br>                                ) { boards, spots, rentals -&gt;<br>                                    UserState.Loaded(user, boards, spots, rentals)<br>                                }<br>                            } else {<br>                                flowOf(UserState.Error(&quot;User profile not found.&quot;))<br>                            }<br>                        }<br>                        is Result.Failure -&gt; {<br>                            flowOf(UserState.Error(<br>                                userResult.error?.message ?: &quot;Failed to load profile.&quot;<br>                            ))<br>                        }<br>                    }<br>                }<br>                .distinctUntilChanged()<br>                .catch { e -&gt; emit(UserState.Error(e.message ?: &quot;Unexpected error&quot;)) }<br>                .collect { _uiState.value = it }<br>        }<br>    }<br>}</pre><p>scope.launch uses the BaseViewModel scope — on Android it&#39;s viewModelScope, on iOS it&#39;s the manually managed CoroutineScope. The ViewModel itself doesn&#39;t know or care which platform it&#39;s running on.</p><h3>Layer 2: The Swift Wrapper with SKIE</h3><p>On iOS, I don’t expose the StateFlow directly to SwiftUI. Instead, each screen has a lightweight ObservableObject wrapper that uses <strong>SKIE</strong> (Swift Kotlin Interface Enhancer) to consume the Kotlin flow with Swift&#39;s native for await syntax, no manual coroutine handling:</p><p>swift</p><pre>// iOS — ProfileScreen wrapper using SKIE for clean async observation<br>extension ProfileScreen {<br>@MainActor<br>    class ProfileScreenModelWrapper: ObservableObject {<br>        let viewModel: UserViewModel<br>        @Published var uiState: UserState<br>        init() {<br>            // Koin provides the ViewModel - no constructor arguments needed<br>            self.viewModel = KoinKt.userViewModel()<br>            self.uiState = viewModel.uiState.value<br>        }<br>        func startObserving() {<br>            Task {<br>                // SKIE makes Kotlin StateFlow iterable with Swift&#39;s for-await<br>                for await state in viewModel.uiState {<br>                    self.uiState = state<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>And the SwiftUI view is completely clean:</p><p>swift</p><pre>struct ProfileScreen: View {<br>    // @StateObject — critical. @ObservedObject can recreate the wrapper<br>    // on re-render, silently cancelling your scope mid-flow.<br>    // This cost me a debugging session I&#39;d rather forget.<br>    @StateObject private var wrapper = ProfileScreenModelWrapper()<br>    var body: some View {<br>            Group {<br>                switch wrapper.uiState {<br>                case .loading:<br>                    LoadingAnimation()<br>                case .error(let message):<br>                    ErrorContent(message: message)<br>                case .loaded(let user, _, _, _):<br>                    ProfileContent(user: user)<br>                }<br>            }<br>            .onAppear { wrapper.startObserving() }<br>            .onDisappear { wrapper.viewModel.clear() } // cancels the iOS CoroutineScope<br>        }<br>    }</pre><h3>Why This Split Works</h3><p>ResponsibilityWhere it livesCoroutine scope lifecycleexpect/actual BaseViewModelBusiness logic &amp; stateShared UserViewModel (commonMain)Flow → SwiftUI bridgeSwift ObservableObject wrapper + SKIEUI renderingJetpack Compose / SwiftUI (100% native)</p><p>Each layer has one owner, one job, and one reason to change.</p><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xALXKWyQzthUMH2-8IQrQw.png" /></figure><h3>Key Lessons</h3><p><strong>1. Draw the line at the Domain layer.</strong> commonMain owns UseCases, Repositories, Models, and ViewModels. It does not own UI state adaptation that belongs to the platform.</p><p><strong>2. </strong><strong>expect/</strong><strong>actual isn&#39;t just for utilities.</strong> Most examples use it for logging or UUID generation. Using it for BaseViewModel means lifecycle is handled correctly everywhere with zero per-screen boilerplate.</p><p><strong>3. Use SKIE.</strong> Consuming Kotlin Flows in Swift without SKIE means writing manual coroutine management in every wrapper. SKIE makes StateFlow directly iterable with for await the wrapper becomes trivial to write.</p><p><strong>4. </strong><strong>@StateObject, not </strong><strong>@ObservedObject.</strong> @ObservedObject can recreate your wrapper on re-render, silently losing all in-flight state. Always use @StateObject for wrappers that own a Kotlin ViewModel.</p><p><strong>5. Don’t forget </strong><strong>clear() on </strong><strong>onDisappear.</strong> On IOS, the coroutine scope doesn&#39;t cancel itself. One missing clear() call and you have a leak running background work on a screen the user already left.</p><p><em>Running into a different KMP pattern that solved these problems better? I’d love to hear about it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e19b078337" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>