<?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 Upretyhemnath on Medium]]></title>
        <description><![CDATA[Stories by Upretyhemnath on Medium]]></description>
        <link>https://medium.com/@upretyhemnath?source=rss-312b8bf967f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kGspt7tT1xMM8Fqy</url>
            <title>Stories by Upretyhemnath on Medium</title>
            <link>https://medium.com/@upretyhemnath?source=rss-312b8bf967f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:48:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@upretyhemnath/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[My Flutter Web Site Is 737 KB. That Number Is a Lie.]]></title>
            <link>https://medium.com/@upretyhemnath/my-flutter-web-site-is-737-kb-that-number-is-a-lie-12ad3357ad16?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ad3357ad16</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter-web-deployment]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 00:00:52 GMT</pubDate>
            <atom:updated>2026-08-10T10:13:17.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sIeM7J8uCWXJpOiI.jpg" /></figure><p>I build mobile apps, so when I rebuilt my portfolio I reached for Flutter. One language, a design system I already had, my own widgets.</p><p>It works, and I’d do it again. But I wrote a build script that prints what a first-time visitor actually downloads, and the result was uncomfortable enough that it changed how I deploy — and made me write part of my own site in plain HTML instead.</p><p>Here’s the full accounting, measured this week.</p><h3>The number everyone quotes</h3><p>main.dart.js - the compiled Dart - comes to <strong>2,508 KB raw, 737 KB gzipped</strong>.</p><p>That’s the figure that ends up in blog posts, and on its own it’s fine. A 737 KB JavaScript payload is heavy but not scandalous.</p><p>It is also not what your visitor downloads.</p><h3>The number nobody quotes</h3><p>Here’s the real output of my release build, every file over 50 KB:</p><pre>RAW GZIP FILE 6917K 2783K canvaskit/canvaskit.wasm 4929K 2186K canvaskit/skwasm_heavy.wasm 3468K 1477K canvaskit/skwasm.wasm 2508K 737K main.dart.js 2195K 813K main.dart.wasm 612K 610K assets/images/background.jpg 416K 412K assets/images/bg_img_2.png 255K 254K assets/images/work_visit_annapurna_app.png 250K 243K assets/images/hemnath1.webp 210K 208K assets/images/work_talent_lockr_app.png ----------------------------------------------------------------- 23625K 10947K TOTAL</pre><p><strong>Let me be precise about that total, because it would be easy to be dishonest here:</strong> 23 MB is what sits in the build directory, not what any one visitor downloads. Flutter ships several renderer variants and the browser picks one.</p><p>But work out what a single visitor on a modern browser actually pulls:</p><p><strong>3.2 MB, not 737 KB.</strong> The compiled Dart is under a quarter of it. The single largest thing my site ships is a rendering engine I didn’t write and can’t shrink.</p><p>That’s the honest headline for Flutter Web, and I’ve never seen it stated plainly: <em>you are not shipping an app, you are shipping an app plus a graphics engine.</em></p><h3>What I could actually fix</h3><p>Two things, and neither was the Dart.</p><p><strong>The images.</strong> Look at that table again: background.jpg is 612 KB raw and <strong>610 KB gzipped</strong>. Compression does nothing for already-compressed formats - a fact that&#39;s obvious once stated and easy to forget when you&#39;re staring at a gzip column. My images are ~1.9 MB and essentially incompressible. That is the biggest lever I have, and it&#39;s a lever every web developer already knows about: resize, re-encode to WebP/AVIF, serve responsive sizes. Nothing Flutter-specific.</p><p><strong>The renderer origin.</strong> By default, Flutter fetches the CanvasKit/skwasm runtime from www.gstatic.com at startup - over a megabyte from a third party, on the critical path, that you cannot cache-control or version-pin. One flag moves it onto your own origin:</p><pre>flutter build web --release --no-web-resources-cdn --wasm</pre><p>It doesn’t make the download smaller. It makes it <em>yours</em> — same-origin, covered by your cache headers, no third-party request before your page paints.</p><h3>Compression is your host’s job, and it’s invisible locally</h3><p>That gzip column is what a <em>correctly configured</em> host serves. If your host doesn’t compress, visitors get the raw column — 2,508 KB instead of 737 KB for the Dart alone.</p><p>This never shows up in development. flutter run -d chrome tells you nothing. flutter build web prints no warning. You can ship a site three times heavier than you believe and never see it.</p><p>So verify against the deployed site, which is the only measurement that counts:</p><pre>curl -sI -H &#39;Accept-Encoding: gzip, br&#39; https://your-domain/main.dart.js \ | grep -i content-encoding</pre><p>Nothing printed means your users are downloading the raw column. Vercel, Netlify and Firebase Hosting all compress automatically; a bare nginx or an S3 bucket does not until you tell it to. Thirty seconds to check.</p><p>Here’s the reporting loop from my build script — the part that made all of this visible:</p><pre>while IFS= read -r file; do raw=$(wc -c &lt;&quot;$file&quot; | tr -d &#39; &#39;) gz=$(gzip -9 -c &quot;$file&quot; | wc -c | tr -d &#39; &#39;) if [[ $raw -gt 51200 ]]; then printf &#39;%11sK %11sK %s\n&#39; &quot;$((raw / 1024))&quot; &quot;$((gz / 1024))&quot; &quot;${file#build/web/}&quot; fi done &lt; &lt;(find build/web -type f \ \( -name &#39;*.js&#39; -o -name &#39;*.wasm&#39; -o -name &#39;*.ttf&#39; -o -name &#39;*.png&#39; \ -o -name &#39;*.jpg&#39; -o -name &#39;*.webp&#39; \) | sort)</pre><p>Twenty lines. I’d add it to any Flutter Web project on day one.</p><h3>The other problem: crawlers see nothing</h3><p>Flutter renders to a &lt;canvas&gt;. Not &quot;mostly canvas&quot; - the DOM contains no headings, no paragraphs, no anchor tags. Zero semantic HTML.</p><p>For a dashboard behind a login, irrelevant. For a <strong>portfolio</strong>, whose entire job is to be found when someone searches your name, close to fatal.</p><p>Two mitigations, and you need both. A &lt;noscript&gt; block holding the real content - Flutter clears &lt;body&gt; on boot, so it never double-renders:</p><pre>&lt;noscript&gt; &lt;h1&gt;Hemnath Uprety - Mobile App Developer&lt;/h1&gt; &lt;p&gt;Mobile app developer with over eleven years of experience...&lt;/p&gt; &lt;/noscript&gt;</pre><p>And JSON-LD in the &lt;head&gt;, which is plain text regardless of what the canvas does:</p><pre>&lt;script type=&quot;application/ld+json&quot;&gt; { &quot;@context&quot;: &quot;https://schema.org&quot;, &quot;@type&quot;: &quot;Person&quot;, &quot;name&quot;: &quot;Hemnath Uprety&quot;, &quot;jobTitle&quot;: &quot;Mobile App Developer&quot; } &lt;/script&gt;</pre><p>The cost nobody mentions: that &lt;noscript&gt; block is a <strong>second copy of your content</strong>, and it will drift from the widgets it mirrors. I keep mine in sync deliberately. That&#39;s a maintenance tax I accepted knowingly rather than discovered later.</p><h3>Where I gave up and wrote HTML</h3><p>Adding a blog is where the canvas stopped being manageable.</p><p>A blog post is 1,500 words that exist <em>to be indexed</em>. Putting them in a canvas and maintaining a shadow copy in &lt;noscript&gt; is absurd. And Medium&#39;s article importer - which reads a URL, builds a draft, and sets the canonical link back to your domain - needs real HTML too. It would have found an empty page.</p><p>So the posts are static HTML files in web/blog/. Flutter copies everything in web/ into the build output verbatim, so they ship with the app and are served without Flutter booting at all. Same fonts, same colour tokens, no framework, no canvas.</p><p>About 1,400 words of this post are readable in the DOM. Zero words of my homepage are.</p><p><strong>If your site is mostly content, don’t render it to a canvas.</strong> I had to build it wrong first to be certain.</p><h3>WasmGC is real, and it’s the default direction</h3><p>Flutter’s 2026 roadmap makes WebAssembly the default web target, and support has arrived — Chrome 119+, Firefox 120+, Safari 18.2+, roughly 92% of global traffic. Reported gains are meaningful: on the order of 25–40% faster initial paint and 15–30% better frame rates on animation-heavy screens.</p><p>My own build backs up the direction: main.dart.wasm is 2,195 KB raw against main.dart.js at 2,508 KB, and it starts faster.</p><p>Two caveats. You still ship a renderer either way — Wasm changes how your Dart executes, it doesn’t delete the engine beside it. And you’re maintaining two outputs, because that remaining ~8% of traffic falls back to JS. My build script takes --no-wasm for exactly that reason: when something breaks I need to know which side broke.</p><h3>One more: the font request you didn’t make</h3><p>If you don’t declare a font family, Flutter Web falls back to Roboto and <strong>fetches it from </strong><strong>fonts.gstatic.com at runtime</strong> - a third-party request on every cold load that you never wrote. For European visitors that&#39;s also a GDPR consideration, since it hands over an IP before anyone agreed to anything.</p><p>Registering your own families isn’t enough. The engine prepares Roboto unless a family <em>by that name</em> exists, so you must register a local Roboto specifically to suppress it:</p><pre>fonts: - family: SpaceGrotesk fonts: [{ asset: assets/fonts/SpaceGrotesk-Bold.ttf, weight: 700 }] # Not used by any widget. Registering it locally is the only way to stop # the engine fetching Roboto from fonts.gstatic.com at runtime. - family: Roboto fonts: [{ asset: assets/fonts/Roboto-Regular.ttf, weight: 400 }]</pre><p>That last block looks like dead config. It’s the opposite — it removes a network request from every page load.</p><h3>So: should you use Flutter for the web?</h3><p>Whichever side you land on, do these four things before calling it shipped:</p><ol><li>Print raw <strong>and</strong> gzipped sizes for every asset over 50 KB.</li><li>curl the deployed bundle and confirm content-encoding.</li><li>Load the page with JavaScript disabled and read what’s left.</li><li>Open the network tab and check whose fonts and whose renderer you’re loading.</li></ol><p>None of that is in the getting-started guide. All of it changed what I shipped.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/flutter-web-honest-numbers/"><em>https://hemnath.com.np</em></a><em> on August 9, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ad3357ad16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Let an AI Write Part of My App. Here’s the Rule I Had to Make.]]></title>
            <link>https://medium.com/@upretyhemnath/i-let-an-ai-write-part-of-my-app-heres-the-rule-i-had-to-make-f795dd740de3?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f795dd740de3</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 00:00:00 GMT</pubDate>
            <atom:updated>2026-08-10T11:14:05.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pm9GYp9jAS5FMJ0H.jpg" /></figure><p>I’ve been using an AI coding agent on real work. Not a weekend project — three codebases I’m responsible for, in three different stacks:</p><ul><li>A <strong>Kotlin Multiplatform</strong> factory-floor app: Compose Multiplatform UI, Ktor, Koin, shared across Android and iOS.</li><li>A <strong>TypeScript monorepo</strong>: NestJS backend, Prisma against Postgres, React frontends, plus firmware for ESP32 scan stations and a Raspberry Pi bridge.</li><li>A <strong>Flutter</strong> web portfolio.</li></ul><p>That range is the point. The agent’s usefulness turned out to vary enormously by stack, by task, and — most of all — by how much context I’d bothered to give it.</p><p>Most writing on this is either “AI replaces developers” or “AI writes garbage”. Neither survives two years of daily use. Here’s the honest version.</p><h3>The single highest-leverage thing I did</h3><p>Not a prompt. A file.</p><p>Both serious projects have a CLAUDE.md at the root - a document describing what the project <em>is</em>, what its invariants are, and where the bodies are buried. Mine is about 12 KB. It covers the monorepo layout, the commands that actually work, how multi-tenancy is enforced, which Prisma models are renamed in the database versus the code, and the migration procedure that hangs against a connection pooler.</p><p>Before that file existed, every session started with the agent rediscovering the project, usually incorrectly. After it, the agent starts where a competent new hire would after a week.</p><p>The clearest example is an invariant I had to write down in blunt terms, because it kept getting re-broken:</p><blockquote><em>A component’s aux-ness is </em><em>primaryProcess === &#39;AUXILIARY_CUTTING&#39; - </em><strong><em>never</em></strong><em> </em><em>materialRole. The </em><em>AUX enum value was removed in migration </em><em>20260728000000; do not reintroduce it or gate any behaviour on it.</em></blockquote><p>That’s a rule with real consequences — get it wrong and certain garments silently never match a template. It’s also completely invisible in the code, because it’s a rule about a value that <em>no longer exists</em>. No amount of reading the repository would recover it.</p><p>Writing that down had an effect I didn’t anticipate: <strong>it made me a better documenter of my own reasoning.</strong> I’d always kept decisions like that in my head. Now the why is written where the next person — human or otherwise — will find it. My repos are better documented than they’ve ever been, for slightly cynical reasons.</p><h3>Where it clearly wins</h3><p><strong>Boilerplate with a known shape.</strong> A Room DAO, a Ktor client, a Prisma migration, a Gradle module wired like the four beside it. Determined entirely by context that already exists in the repo. Fast, and right, because there’s little to get wrong.</p><p><strong>Reading unfamiliar code.</strong> “Where does the bundle status transition get enforced?” across a monorepo with a NestJS backend and two React apps is a search I’d do with grep and three wrong guesses. This is the use I’d give up last.</p><p><strong>Crossing stacks.</strong> This is where it changed my work most. That ERP spans TypeScript, SQL, Kotlin, and embedded C for the scan stations. I am not equally fluent in all four. Having something that’s competent in all of them, in the same session, closes a gap I used to close by context-switching for a day.</p><p><strong>Measurement and scaffolding.</strong> I asked for a build script reporting raw and gzipped payload sizes for a Flutter Web build. Twenty lines of bash I’d have deferred indefinitely. It surfaced that the site ships a 612 KB background image that gzip cannot compress at all — a real finding I wasn’t looking for.</p><h3>Where it costs you</h3><p><strong>Confident, plausible wrongness.</strong> This is the whole risk, and it doesn’t look like an error. It looks like working code with a wrong assumption inside.</p><p>The pattern I’ve been burned by most: code that respects the <em>shape</em> of a codebase convention while violating its <em>meaning</em>. Generated code that checks the right field with the wrong semantics, or matches an enum that was deliberately retired. It compiles. It runs. It produces plausible output. And it’s wrong in a way that tests written from the same misunderstanding will happily confirm.</p><p><strong>Plausible APIs that don’t exist.</strong> Less dangerous — it fails at compile time — but it wastes real minutes, especially on fast-moving libraries where the agent’s sense of the API blends three versions. Compose Multiplatform, being young, is the worst offender in my stacks.</p><p><strong>The review tax.</strong> Reviewing 200 lines you didn’t write is slower than writing 100 yourself. Skip that review and you’ve traded a known cost for an unknown one, and the unknown one arrives during a release.</p><h3>The rule I settled on</h3><blockquote><strong><em>I do not accept code I could not have written myself.</em></strong></blockquote><p>Not “would not have” — <em>could not have</em>. If it produces something using a pattern I don’t understand, I either learn it properly before it lands, or I don’t take it.</p><p>The reasoning is simple: I’m the one who gets called when the factory floor stops scanning at 6am. Code in my repo that I can’t debug is a liability regardless of authorship, and “the AI wrote that part” is not a sentence you can say to a client.</p><p>That rule sorts everything else. Boilerplate passes trivially — I know what a DAO does. A clever concurrency trick doesn’t, so I either learn it or write a simpler thing I trust.</p><h3>How I actually review it</h3><p><strong>1. Does it match the existing code?</strong> Not just style — the same error handling, the same result types, the same layering. Generated code that ignores your Resource type and returns raw nullables is a slow leak in your architecture.</p><p><strong>2. What happens on the failure path?</strong> Generated code is optimistic. It handles the 200 and shrugs at the timeout, the 401, the malformed body. This is where I find the most problems, every time.</p><p><strong>3. Are the constants real?</strong> Version numbers, endpoints, header names, magic numbers. Exactly what a language model produces plausibly and wrongly. I check against docs, not against my memory of docs.</p><p><strong>4. Would I have written a test for this?</strong> If yes, write it — <em>yourself</em>. A test generated from the same misunderstanding as the code will pass and prove nothing. This one matters more than it sounds.</p><h3>What surprised me</h3><p><strong>It’s better at deleting than adding.</strong> Point it at a directory and ask what’s redundant, and it finds duplication across modules I’d stopped seeing. Deletion is also the safest operation — the failure mode is a compile error, not a silent bug.</p><p><strong>It’s better with more constraint, not less.</strong> “Write a login screen” produces something generic. “Write a login screen using the BaseUiState in this repo, matching the error handling in AuthUseCase, with errorType set for empty-field validation&quot; produces something usable. <strong>The specification is the work.</strong> That hasn&#39;t changed, and I don&#39;t think it will.</p><p><strong>It’s a genuine equaliser for solo work.</strong> I do a lot of contract work alone. Having something to check an approach against — even something sometimes wrong — is closer to having a colleague than to having a tool. I don’t think that gets said enough by people writing from inside large teams.</p><p><strong>The commit messages stay mine.</strong> My project instructions say never to mention an AI assistant in a commit message or add a co-author trailer. That’s deliberate: the commit history is a record of decisions, and I made them. Attribution belongs to whoever is accountable, and that’s me.</p><h3>What I won’t hand over</h3><p><strong>Architecture decisions.</strong> Where module boundaries go, whether stock is an append-only ledger, whether a conflict resolves last-write-wins or field-level merge. These depend on things not in the repo — who the users are, what the client can maintain, what a failure costs. The agent doesn’t know that a flood warning being four hours stale is a different category of problem from a stale profile photo.</p><p><strong>Anything touching credentials, money, or crypto.</strong> Not because it’s necessarily worse there, but because “plausible and wrong” has a much higher cost and I can’t always spot it by reading.</p><p><strong>The final read of anything going to production.</strong> Someone has to have read every line. That’s me. It was true before, and it’s more true now that the volume arriving is higher.</p><h3>The honest summary</h3><p>It’s a fast, tireless colleague with enormous breadth and no stake in the outcome. Everything good I’ve gotten out of it came from treating it that way: clear scope, written-down context, code I can check, and never the decision that requires knowing why the project exists.</p><p>It made me faster across four languages I couldn’t have kept equally sharp on my own. It did not make me less responsible — and the moments it cost me were, every time, the moments I acted as though it had.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/ai-assisted-development/"><em>https://hemnath.com.np</em></a><em> on July 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f795dd740de3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP or Flutter? I Ship Both. Here’s How I Actually Decide.]]></title>
            <link>https://medium.com/@upretyhemnath/kmp-or-flutter-i-ship-both-heres-how-i-actually-decide-5596c03e198a?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5596c03e198a</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 00:00:01 GMT</pubDate>
            <atom:updated>2026-08-10T11:11:55.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WSX806KJ0hxEDVBz.jpg" /></figure><p>Almost every KMP-versus-Flutter post is written by someone who only uses one of them. That’s the problem with the genre: the conclusion is set before the first paragraph.</p><p>I’ve spent eleven years in native Android — Kotlin and Java — and the last few shipping Flutter and React Native alongside it. Right now I’m building a factory-floor app in Kotlin Multiplatform while maintaining Flutter work. I have no side to defend, and I’ve picked wrong in both directions.</p><p>Here’s the framework I actually use, plus real numbers from the KMP app I’m in this week.</p><h3>There are three options, not two</h3><p>This is where most comparisons go wrong, and I made the same mistake before I shipped KMP myself.</p><p><strong>Flutter</strong> shares the UI. One widget tree, Flutter’s own rendering engine painting to a canvas everywhere. Your buttons are Flutter’s buttons on both platforms.</p><p><strong>KMP with native UI</strong> shares the logic only. Networking, models, validation and business rules live in commonMain; the screens are SwiftUI on iOS and Compose on Android. This is the version everyone describes, and it&#39;s the one Netflix and Cash App are usually cited for.</p><p><strong>KMP with Compose Multiplatform</strong> shares the UI <em>as well</em> — Compose renders on both platforms, and your shared module holds screens, not just repositories.</p><p>That third option is the one comparison tables forget, and it’s the one I’m shipping. It changes the trade-off completely: you get Kotlin end to end, one UI codebase, and no Dart — but you also give up the “native look by default” argument that’s usually KMP’s headline advantage.</p><p>So the real question isn’t “KMP or Flutter”. It’s <strong>how much do you want to share, and in which language.</strong></p><h3>What it actually looks like</h3><p>Numbers from the app I’m building — a factory-floor tool for garment production, scanning QR-tagged work bundles through a manufacturing pipeline:</p><ul><li><strong>176 Kotlin files in </strong><strong>commonMain</strong>, including the UI</li><li><strong>6 </strong><strong>expect declarations</strong> in the entire shared module</li><li>Ktor for HTTP, Koin for DI, kotlinx.serialization, kotlinx.datetime, DataStore for preferences</li><li>androidApp and iosApp are thin entry points</li></ul><p>Six. That’s the number I’d point at, because the fear people have about KMP is that platform-specific code metastasises. Here’s the complete list of what genuinely needed it:</p><pre>expect fun getPlatform(): Platform expect fun platformImageDecoders(): List&lt;Decoder.Factory&gt; expect val platformModule: Module // Koin: platform bindings expect fun defaultApiBaseUrl(): String expect class PushTokenProvider() expect fun rememberGalleryQrPicker(...)</pre><p>Push tokens, image decoding, a QR picker that reaches into the photo library, and the DI module that wires them. Every one of those is genuinely a platform capability. <strong>None of the business logic is duplicated.</strong></p><p>The rule I’d give: <em>if you’re writing </em><em>expect/</em><em>actual for anything that isn&#39;t a platform capability, your boundary is in the wrong place.</em> Six declarations for 176 files is what healthy looks like. If it&#39;s spreading into your domain layer, you&#39;re writing two apps that share a folder.</p><p>A repository in commonMain, compiled for both platforms, with no platform imports at all:</p><pre>class BundleRepository( private val client: HttpClient, private val store: BundleStore, ) { fun observe(stationId: String): Flow&lt;Resource&lt;List&lt;Bundle&gt;&gt;&gt; = flow { emit(Resource.Loading()) emit(Resource.Success(store.cached(stationId))) // instant, from disk try { val fresh: List&lt;Bundle&gt; = client.get(&quot;bundles&quot;) { parameter(&quot;station&quot;, stationId) }.body() store.replace(stationId, fresh) emit(Resource.Success(fresh)) } catch (e: Exception) { emit(Resource.Error(e.toUserMessage())) } } }</pre><p>Ktor, kotlinx.serialization, coroutines Flow - all multiplatform. The same file runs on both phones.</p><p><strong>On DI:</strong> Hilt is Android-only, so a shared module rules it out. Koin is the pragmatic multiplatform answer, and the cost is real — runtime resolution instead of Dagger’s compile-time verification. You find a missing binding when the screen opens, not when the build runs. I’ve made peace with it; you should know you’re making the trade.</p><p><strong>On Swift interop:</strong> if you go the native-UI route, know that Flow doesn&#39;t cross to Swift cleanly on its own. You wrap it, or use SKIE or KMP-NativeCoroutines. Budget for it - it surprises teams. Compose Multiplatform sidesteps this entirely, which is a quiet argument in its favour.</p><h3>The honest trade-offs</h3><p>Two rows decide most real projects.</p><p><strong>Incremental adoption.</strong> KMP can enter an existing native app one module at a time — move networking into commonMain, ship, move the next thing. Flutter in a live native app is technically possible and practically a rewrite. If you have users today, that difference is enormous.</p><p><strong>Ecosystem maturity.</strong> This is where I’d temper my own enthusiasm. Flutter’s package ecosystem is deeper, its answers are better documented, and when something breaks at 11pm there is usually a Stack Overflow answer. Compose Multiplatform is younger. I hit rougher edges on iOS and solved them by reading source rather than docs. Worth knowing before you commit a team.</p><h3>How I actually choose</h3><p>Four questions, in order. The first with a clear answer wins.</p><p><strong>1. Does an app already exist and have users?</strong> Yes → KMP. Incremental adoption is the whole argument; you keep shipping while you migrate.</p><p><strong>2. What language does the team actually write?</strong> A Kotlin team → KMP, and probably Compose Multiplatform. Asking Android developers to become Dart developers is a real cost that comparison tables never price. A team already in Flutter → stay in Flutter.</p><p><strong>3. How much does native feel matter?</strong> A consumer app on iOS where users notice non-standard scrolling and pickers → KMP with native SwiftUI. An internal tool, a factory floor app, a B2B dashboard → nobody cares, and shared UI wins on cost.</p><p><strong>4. Is there a web or desktop target?</strong> Flutter covers both from one codebase today. Compose Multiplatform has stable Android/iOS/desktop with web still maturing. But read my <a href="https://hemnath.com.np/blog/flutter-web-honest-numbers">measurements on Flutter Web</a> before counting it free — it’s viable for dashboards, not for content.</p><p>For the factory app, questions 2 and 3 both pointed the same way: a Kotlin codebase, an internal tool where platform-idiomatic scrolling is nobody’s priority. Compose Multiplatform was straightforward.</p><h3>The case neither camp mentions</h3><p>Sometimes the answer is neither.</p><p>A single-platform app should be single-platform. If 95% of your users are on Android — true for a great deal of the work I do in Nepal — then Compose and Kotlin with no abstraction layer beats both options on every axis. You ship faster, debug in one place, and use every platform API the day it lands.</p><p>Cross-platform solves <em>having two platforms</em>. Check you have that problem before paying for the fix.</p><h3>What I’d tell a team deciding this week</h3><p>Build the same feature twice, once in each, before committing. Not a to-do list — pick the ugliest real thing in your product: pagination, an error state, a cache, and one platform-specific capability like the camera. It takes a week and it will tell you more than any comparison table, this one included.</p><p>And whichever you choose, put the boundary in the same place: <strong>the UI layer should never know where its data came from.</strong> Get that right and the decision stays reversible, which is the only property that actually protects you.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/kmp-vs-flutter/"><em>https://hemnath.com.np</em></a><em> on July 14, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5596c03e198a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AR App on Three Google SDKs. Google Killed All Three.]]></title>
            <link>https://medium.com/@upretyhemnath/i-built-an-ar-app-on-three-google-sdks-google-killed-all-three-b0e2161f5861?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0e2161f5861</guid>
            <category><![CDATA[ar-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 00:00:16 GMT</pubDate>
            <atom:updated>2026-08-10T11:08:48.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LgEcGlAv82t8nxIy.jpg" /></figure><p>In 2019 I built an augmented-reality guide to the cultural and natural landmarks of Nepal’s Annapurna region. Point your phone at a mountain, get its name and story floating over it. Walk toward a temple, see the marker anchored to the real world. Tap it for a 360° panorama.</p><p>It shipped. It worked. It was, at the time, built on the officially recommended stack:</p><pre>implementation &#39;com.google.ar.sceneform:core:1.17.1&#39; implementation &#39;com.google.ar.sceneform.ux:sceneform-ux:1.17.1&#39; implementation &#39;com.github.appoly:ARCore-Location:1.2&#39; implementation &#39;com.google.vr:sdk-panowidget:1.180.0&#39;</pre><p>Sceneform was Google’s 3D framework for ARCore. The VR SDK’s VrPanoramaView was Google&#39;s 360° viewer. Between them they were most of the app.</p><p>Google archived Sceneform in 2020. The Google VR SDK was deprecated and archived too. ARCore-Location, the community library doing the geospatial anchoring, was built on top of the first one.</p><p>Three dependencies. Three dead. The app still runs, and none of it can be maintained the way it was written.</p><p>This post is about what I’d do differently, and it isn’t “don’t use AR”.</p><h3>What the app actually did</h3><p>Worth being concrete, because “AR app” covers a lot of ground.</p><p><strong>Location-anchored markers.</strong> Not surface detection, not plane tracking — the interesting part was placing a label on a mountain seven kilometres away. That’s a GPS coordinate plus a compass bearing plus device attitude, projected into the camera view. ARCore-Location did the maths; ARCore&#39;s Session supplied the pose.</p><p><strong>360° panoramas.</strong> Tap a landmark, get an immersive photosphere via VrPanoramaView. Eight of them in the codebase, the highest-value content in the app and the cheapest to produce - a photographer with a 360 camera, not a 3D artist.</p><p><strong>A plain list view.</strong> Which mattered more than any of the AR. More on that below.</p><h3>Lesson one: the AR was the least durable part, and the least used</h3><p>Here’s the thing nobody tells you before you build an AR app.</p><p>Users open the camera view once. They enjoy it. Then, for the rest of the trip, they use the list.</p><p>Augmented reality is spectacular in a demo and awkward in practice: you hold a phone at arm’s length, in sunlight, with a battery draining at 15% an hour, while trying to also walk. On a trekking route, at altitude, with cold hands, the list wins every time.</p><p>The list view still works today, exactly as written, on every Android version since. It depends on nothing that can be discontinued.</p><p><strong>If I built this again</strong>, I’d build the same content with AR as one <em>view</em> over a data model that doesn’t know AR exists — not as the app’s organising principle. That isn’t a retreat from AR. It’s recognising that landmark data, photos and descriptions are the durable asset, and the camera overlay is a presentation of them.</p><h3>Lesson two: the deprecation risk was visible in advance, if I’d looked</h3><p>I want to be fair to my past self and honest at the same time.</p><p>Sceneform was Google’s official recommendation when I chose it. That’s not a careless decision. But the signals were there:</p><ul><li>It was a <strong>convenience layer</strong>, not the core. ARCore itself — the tracking, the Session, the pose estimation - is still alive and supported today. Sceneform was the rendering sugar on top, and sugar layers are what vendors drop.</li><li>It <strong>wasn’t used by Google’s own major products.</strong></li><li>Its release cadence had already slowed before the archive notice.</li></ul><p>The rule I took from it: <strong>depend on the layer the vendor cannot afford to drop.</strong> ARCore is a platform capability Google needs. Sceneform was a convenience. When you’re picking between them, ask which one the vendor would still ship if the team were cut in half.</p><p>Today the equivalent choice would be ARCore plus a general-purpose renderer — Filament, which Google also maintains but which has a life beyond AR, or a game engine. More work up front. It doesn’t get archived out from under you.</p><h3>Lesson three: isolate the vendor, always</h3><p>This is the part that generalises past AR, and it’s the mistake I’d actually fix.</p><p>Sceneform types were spread through my activities. ArSceneView in the layout, Anchor in the fragment, renderable construction in the click handler. When the framework died, there was no seam to cut along - replacing it meant touching everything that touched AR.</p><p>What that should have looked like:</p><pre>/** * Everything the app needs from an AR framework, and nothing about which one. * The point is that this interface names *landmarks*, not renderables - if the * vendor&#39;s vocabulary leaks in here, the abstraction is already broken. */ interface LandmarkAugmenter { fun start(surface: SurfaceProvider) fun show(landmarks: List&lt;Landmark&gt;) fun onLandmarkTapped(handler: (Landmark) -&gt; Unit) fun stop() }</pre><p>One implementation for Sceneform, and when it died, one new implementation. The rest of the app — the list, the detail screens, the panoramas, the data layer — never learns that anything changed.</p><p>This is the same argument I make about <a href="https://hemnath.com.np/blog/clean-architecture">module boundaries</a> and about <a href="https://hemnath.com.np/blog/kmp-vs-flutter">keeping the UI layer ignorant of its data source</a>. The vendor SDK is just another thing the rest of your code shouldn’t know about. The measure of a good boundary isn’t elegance — it’s how much has to change when what’s behind it goes away.</p><p><strong>How much work is that?</strong> Genuinely, a day. I didn’t do it because the app was small and the deadline was real, and that was a defensible call at the time. The bill arrived four years later, which is exactly how this kind of debt works.</p><h3>Lesson four: prefer boring content formats</h3><p>The 360° panoramas were served by VrPanoramaView, which is also archived. But the <em>panoramas</em> are equirectangular JPEGs - a format that predates the SDK and outlived it.</p><p>Swapping the viewer is a contained problem precisely because the content is boring. Had I used a proprietary scene format tied to Sceneform, the content itself would have needed regenerating.</p><p><strong>Store content in formats that don’t belong to anyone.</strong> Equirectangular JPEG, glTF, GeoJSON, plain coordinates. The viewer is replaceable; the asset library is what you actually own.</p><h3>What I’d tell someone building AR today</h3><p><strong>Check whether you need AR or you need a map.</strong> Location-anchored markers at distance are often better served by a compass view or a map with bearings. AR earns its keep when the alignment with the real world is the point — measuring a room, placing furniture, overlaying an engine part. For “what mountain is that”, a bearing and a name may serve users better and cost a tenth as much.</p><p><strong>Budget for battery and sunlight.</strong> Both are worse than any demo suggests. Design a non-AR path for the same task and assume most sessions will use it.</p><p><strong>Pick the lowest-level dependency you can tolerate.</strong> Platform capability over convenience wrapper.</p><p><strong>Put one interface between you and the SDK.</strong> A day of work that buys you the option to survive an archive notice.</p><h3>Was it worth building?</h3><p>Yes — and I’d say that even knowing the stack would die.</p><p>The app did what it was meant to do: it got people to look at landmarks they’d have walked past. The content outlived the framework. And the failure taught me something more transferable than any AR technique, which is that <strong>the half-life of a vendor’s convenience layer is much shorter than the half-life of your app.</strong></p><p>That lesson has been worth more than the AR ever was. It’s why I now ask, about every dependency: if this is archived in three years, how many files do I have to open?</p><p>If the answer is “all of them”, I haven’t finished designing.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/three-dead-sdks/"><em>https://hemnath.com.np</em></a><em> on June 30, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e2161f5861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Background Job Doesn’t Know the Phone Is Overheating]]></title>
            <link>https://medium.com/@upretyhemnath/your-background-job-doesnt-know-the-phone-is-overheating-7113ed2494e2?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7113ed2494e2</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[background-task]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 00:00:15 GMT</pubDate>
            <atom:updated>2026-08-10T11:07:21.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LewPiA9wEAcV9Dme.jpg" /></figure><p>Most background processing on mobile is written as if the device were a server: take the next item, do the work, take the next one. On a laptop that’s fine. On a phone held in a hand, it isn’t — because sustained work heats the SoC, and a hot SoC gets throttled by the kernel until your “fast” queue is crawling and the case is uncomfortable to hold.</p><p>The device is telling you this the whole time. Almost nothing listens.</p><p>I built a queue manager that does: it reads CPU temperature, pauses processing when the phone gets too hot, and resumes when it has cooled. This post is about that, and about the one detail that separates a working version from an infuriating one.</p><h3>The thresholds</h3><p>Start with the shape of the answer:</p><pre>/// Centralized CPU temperature thresholds (in Celsius) class TemperatureThresholds { static const double t1 = 45.0; // safe (green) static const double t2 = 60.0; // warning (yellow) static const double t3 = 70.0; // critical (red) static bool shouldPause(double temperature) =&gt; temperature &gt;= t3; static bool shouldResume(double temperature) =&gt; temperature &lt; t2; }</pre><p>Read those last two lines carefully, because the interesting thing is what they <em>don’t</em> say.</p><p><strong>Pause at 70°C. Resume below 60°C.</strong> Not below 70. Two different numbers.</p><h3>Why two numbers: hysteresis</h3><p>If you pause and resume at the same threshold, you get chattering.</p><p>The device sits at 70.0°C. You pause. It cools to 69.9°C. You resume. Processing immediately pushes it back to 70.1°C. You pause. Over and over, several times a second — a queue that is neither running nor stopped, a UI indicator strobing between red and green, and worse thermals than if you’d simply kept going, because you’re now paying the cost of starting and stopping work continuously.</p><p>The fix is a <strong>hysteresis gap</strong>: the threshold to leave a state is different from the threshold to enter it. It’s the same principle as a household thermostat that heats to 21°C but doesn’t switch on again until 19°C, and the same idea as a Schmitt trigger in electronics.</p><p>Ten degrees of gap means that once you pause, the device has to genuinely cool — usually tens of seconds of real thermal recovery — before work restarts. One state change, not fifty.</p><pre>temp ──────────────────────────────────────────────► 60°C 70°C RUNNING ────────────────────────► PAUSE ◄──────────── resume only after dropping here</pre><p><strong>This is the whole trick, and it applies far beyond temperature.</strong> Any time you gate behaviour on a continuous signal — battery level, network speed, scroll velocity, memory pressure — a single threshold will chatter at the boundary. Two thresholds won’t. I’ve since gone back and put a gap into a “low battery” mode that used to flicker at exactly 15%.</p><h3>Getting the temperature</h3><p>Flutter has no thermal API, so this is a platform channel. Android exposes it two ways, and the difference matters.</p><p>The <strong>modern</strong> route is PowerManager.getCurrentThermalStatus() (API 29+), which returns an abstracted status rather than a number:</p><pre>// THERMAL_STATUS_NONE / LIGHT / MODERATE / SEVERE / CRITICAL / EMERGENCY / SHUTDOWN val status = powerManager.currentThermalStatus</pre><p>This is what Google wants you to use, and for good reason: it’s the OS’s own judgement, it accounts for the whole device rather than one sensor, and it’s stable across hardware.</p><p>The <strong>raw</strong> route is reading thermal zones from sysfs — /sys/class/thermal/thermal_zone*/temp. It gives you an actual number, which is what a temperature <em>gauge</em> in a UI needs. It&#39;s also unreliable in ways worth knowing:</p><ul><li>Zone naming and count differ per SoC. thermal_zone0 is the CPU on one device and the battery on another; you have to read .../type to find out.</li><li>Units vary — usually millidegrees, sometimes degrees.</li><li>Some devices restrict access entirely.</li></ul><p>So: <strong>use </strong><strong>getCurrentThermalStatus() for decisions, and sysfs only for display, treating it as best-effort.</strong> A pause driven by the OS&#39;s own severity signal is correct on every device; a pause driven by &quot;zone 3 says 71&quot; is correct on the devices you tested.</p><pre>// Platform channel, with a defined &quot;we don&#39;t know&quot; case. On a device that // exposes nothing, the queue must keep working - never gate core behaviour // on a signal that may be absent. static const _channel = MethodChannel(&#39;app/cpu_temperature&#39;); Future&lt;ThermalReading&gt; read() async { try { final result = await _channel.invokeMethod&lt;Map&gt;(&#39;getThermal&#39;); return ThermalReading( status: ThermalStatus.values[result![&#39;status&#39;] as int], celsius: (result[&#39;celsius&#39;] as num?)?.toDouble(), // may be null ); } on PlatformException { return ThermalReading.unknown; } }</pre><p>That unknown case is not a formality. If your queue only runs when it can prove the device is cool, it will do nothing at all on hardware that reports nothing.</p><h3>The other half: don’t rewrite 400 rows to move one item</h3><p>The queue is reorderable — users drag items to change processing order. The naive implementation stores an integer position per row, and moving one item renumbers everything after it. Drag an item to the top of a 400-item queue and you&#39;ve written 400 rows.</p><p>On a phone, that’s a slow transaction, a burst of I/O, and — appropriately enough — heat.</p><p><strong>Fractional positioning</strong> fixes it. Store position as a double and insert between neighbours:</p><pre>/// New position for an item dropped between [before] and [after]. /// Moving one item writes exactly one row, regardless of queue length. double positionBetween(double? before, double? after) { if (before == null &amp;&amp; after == null) return 1.0; if (before == null) return after! - 1.0; // new head if (after == null) return before + 1.0; // new tail return (before + after) / 2; // between }</pre><p>One write. Always.</p><p>The catch, and you should know it before shipping: <strong>doubles run out of room.</strong> Repeatedly dropping an item into the same gap halves the interval each time, and after about 50 subdivisions you hit the limits of float precision and two items compare equal. The queue silently stops preserving order.</p><p>Two defences, and you want both:</p><ol><li><strong>Detect it.</strong> After computing, check the gap is still meaningful — if (after - before).abs() &lt; 1e-9, don&#39;t write.</li><li><strong>Renormalise.</strong> When it happens, rewrite the whole list to clean integers, once, in a background transaction. It’s the expensive operation you were avoiding, but now it happens rarely instead of on every drag.</li></ol><p>For a list that will never exceed a few hundred items, doubles are fine with those guards. If you expect adversarial reordering or very large lists, use a string-based ordering key instead — lexicographic ranks subdivide indefinitely because you can always append another character.</p><h3>Putting them together</h3><p>The two halves solve the same problem from opposite ends. Fractional positioning means reordering does almost no work, so it generates almost no heat. Thermal awareness means that when heat arrives from the actual processing, the queue yields instead of fighting the kernel’s throttling.</p><p>And there’s a UX point buried in it. A queue that quietly pauses is indistinguishable from a queue that’s broken. The temperature bands exist as much for the interface as for the logic:</p><blockquote><strong><em>Paused — device is warm.</em></strong><em> Processing resumes automatically once it cools.</em></blockquote><p>That sentence is the difference between a feature and a bug report. Same principle as <a href="https://hemnath.com.np/blog/offline-first">error states that name the real failure</a>: tell the user what’s true and whether they need to act.</p><h3>What I’d tell someone building this</h3><p>Use the OS thermal status for decisions and raw sensors only for display. Put a hysteresis gap on every threshold you act on — and go check the ones you already have, because a single threshold on a noisy signal is a bug that’s been waiting quietly. Store order as a fraction, not an index, and guard the precision floor.</p><p>None of it is exotic. It’s mostly the recognition that a phone is a thermally constrained device holding a battery, and that most of our background-work idioms were written for machines plugged into a wall.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/thermal-aware-queue/"><em>https://hemnath.com.np</em></a><em> on June 11, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7113ed2494e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Android Launcher, Five Products]]></title>
            <link>https://medium.com/@upretyhemnath/one-android-launcher-five-products-5775ea6e21d4?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5775ea6e21d4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-launcher]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 26 May 2026 00:00:25 GMT</pubDate>
            <atom:updated>2026-08-10T11:05:52.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4PrK0fCoVbhOPBNH.jpg" /></figure><p>Replacing the home screen is one of the most invasive things an Android app can do. It’s also, commercially, an attractive place to be: the launcher is the first thing a user sees, every time they unlock the phone.</p><p>I’ve worked on a launcher that ships as several distinct products — different names, different branding, different feature sets, one codebase. This post is about how that’s actually done, and about the point where sharing one codebase across five products starts costing more than it saves.</p><h3>Nobody writes a launcher from scratch</h3><p>First, the honest part: <strong>the launcher engine is AOSP’s Launcher3.</strong> Ours, Lawnchair’s, Nova’s, most of them. The package tree says so plainly:</p><pre>com/android/launcher3/ com/android/launcher3/allapps/ com/android/launcher3/anim/ android/apps/nexuslauncher/</pre><p>That’s not a shortcut, it’s the only sane approach. A home screen has to handle widget hosting, icon packs, work profiles, drag and drop across pages, folder mechanics, live wallpapers, accessibility, and per-OEM behaviour differences — a body of work measured in years, that Google maintains, that has to keep working across every Android release.</p><p>What’s actually yours in a launcher product is everything <em>around</em> the engine: the visual identity, the features you bolt on, the configuration surface, and the release pipeline. That’s where the interesting engineering lives, and it’s a different kind of engineering than people expect.</p><h3>Build variants are the product line</h3><p>Multiple products from one codebase means Gradle does the work:</p><pre>flavorDimensions &quot;brand&quot; productFlavors { imali { applicationId &quot;com.imali.launcher&quot; // ... } home { applicationId &quot;com.homelauncher.launcher&quot; } // ... }</pre><p>Different applicationId per flavour is what makes them genuinely separate apps - separate Play listings, separate installs, coexisting on one device. Everything else follows from that.</p><p>Two things I’d insist on if setting this up again.</p><p><strong>Features are flags, not forks.</strong> The moment “brand B doesn’t have the news feed” becomes a branch instead of a boolean, you have two codebases wearing a trenchcoat. Every feature that varies gets a build-config flag and one code path that reads it.</p><p><strong>Brand values live in one file per flavour, not scattered through resource overlays.</strong> Launcher3 already has a large resource tree; if brand colours and defaults are sprinkled across a dozen values.xml overrides per flavour, nobody can answer &quot;what&#39;s different about brand C?&quot; without diffing directories. One config object, one place to look.</p><h3>The bolt-ons are the product</h3><p>The launcher engine is table stakes. In our tree, the modules alongside it are what differentiate:</p><pre>animationlib/ custom transitions datablocking/ network filtering chatAI/ assistant integration</pre><p>That structure is the right instinct — each is a Gradle module with its own boundary, so a flavour that doesn’t ship the assistant doesn’t compile it. Same argument as <a href="https://hemnath.com.np/blog/clean-architecture">enforcing architecture with the module graph</a>: if :app doesn&#39;t depend on :chatAI, no accidental import can sneak it into a build that shouldn&#39;t have it.</p><p>One of those deserves specific comment. The network filtering is built on <strong>NetGuard</strong>, a mature open-source VpnService firewall — a real packet engine in C, handling TCP, UDP, ICMP, DNS and DHCP without needing root.</p><p>If you bundle something like that, two obligations come with it:</p><p><strong>Licence.</strong> NetGuard is GPLv3. Combining GPLv3 code into a distributed app has consequences for the whole work, and “we put it in a separate module” does not, on its own, create a licence boundary. This is a question for a lawyer before launch, not after.</p><p><strong>User expectation.</strong> A VPN-based filter shows a permanent key icon and routes all traffic through your app. That’s an enormous amount of trust, and it needs to be earned explicitly — a clear explanation before the permission prompt, and no data leaving the device that the user hasn’t been told about. A launcher that quietly starts a VPN is a launcher that deserves the review it will get.</p><h3>Where white-labelling stops paying</h3><p>This is the part I’d want someone to hear before choosing this strategy.</p><p><strong>Sharing works while the products are the same app with different paint.</strong> Different colours, logo, default wallpaper, a feature toggled off — one codebase, five listings, trivial marginal cost. Excellent.</p><p><strong>It stops working when the products want different behaviour.</strong> Brand A wants a vertical app drawer, brand B wants pages. Brand C wants the assistant on the home screen, brand D wants it gone entirely. Each request adds a conditional, and conditionals multiply: five brands and six toggles is a combination space nobody is testing.</p><p>The failure isn’t dramatic. It’s that a change for brand A breaks brand D, nobody notices because nobody ran brand D, and it ships. <strong>The cost of white-labelling is testing, and it grows with the product of your variants, not the sum.</strong></p><p>Two rules I’d hold:</p><ol><li><strong>CI builds every flavour, every time.</strong> If you can’t afford to build five variants on every commit, you can’t afford five variants.</li><li><strong>When a brand needs different behaviour rather than different values, that’s the signal to fork it properly</strong> — and take the maintenance hit honestly, instead of paying it as conditionals forever.</li></ol><h3>Upstream is a treadmill</h3><p>The other cost, and the one that’s easy to underestimate: Launcher3 is a moving target.</p><p>Every Android release changes it — new widget APIs, predictive back, themed icons, work-profile changes, and periodic internal restructuring. Your customisations sit on top of a base that shifts under them once a year, and the further your fork diverges, the more painful each rebase.</p><p>The mitigation is discipline about <em>where</em> you modify. Additive changes in your own modules survive a rebase. Edits scattered through com.android.launcher3 internals do not. Every line you change inside the upstream tree is a line you re-resolve, every year, forever.</p><p>If you take one practical thing from this: <strong>keep a written list of every upstream file you’ve touched and why.</strong> It’s the document that makes next year’s rebase a day instead of a fortnight, and it’s exactly the kind of institutional knowledge that leaves when a developer does.</p><h3>Is it worth it?</h3><p>For a launcher, yes — the alternative is not shipping. Nobody is writing a home screen from scratch, and the engine genuinely isn’t the differentiator.</p><p>But go in knowing what you’re actually signing up for. You’re not maintaining a launcher; you’re maintaining a <em>patch set</em> against one, multiplied by however many products you sell, on an annual upstream cadence you don’t control.</p><p>That’s a real, tractable engineering job. It’s just a different one than “we’re building a launcher”.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/one-launcher-five-products/"><em>https://hemnath.com.np</em></a><em> on May 26, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5775ea6e21d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Flood Warning Is Just a Map Tile With a Deadline]]></title>
            <link>https://medium.com/@upretyhemnath/a-flood-warning-is-just-a-map-tile-with-a-deadline-8d0c5d07a6be?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0c5d07a6be</guid>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 12 May 2026 00:00:57 GMT</pubDate>
            <atom:updated>2026-08-10T11:04:46.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6xh0t9D7OOofZE8P.jpg" /></figure><p>The hardest thing about building a road-hazard app was never the map.</p><p>Dropping a pin with flutter_map is a tutorial. What took the work was everything around it: rainfall forecasts arriving from a European model on their own schedule, flood guidance from a regional system in a format nobody designed for phones, a government map server that answers in 400ms on a good day, and a user standing at a road junction at 6am who needs to know one thing - <em>can I drive this or not?</em></p><p>This post is about the layer between a data source you don’t control and a screen that has to be right.</p><h3>Two kinds of layer, and why it matters</h3><p>Almost every mapping mistake I’ve made came from not separating these.</p><p><strong>Base tiles</strong> are the world: roads, rivers, contours. They change roughly never. OpenStreetMap raster tiles at zoom 6–14 for a country the size of Nepal is a bounded, cacheable quantity.</p><p><strong>Hazard layers</strong> are the news: which bridge is out, where flood guidance is red, where rainfall is forecast past a threshold. They change hourly and they’re worthless stale.</p><p>Treat both as “the map” and you get the worst of each — you re-download roads that haven’t moved since 2019, and you cache a flood warning until it’s a lie. Different fetch strategy, different cache lifetime, different failure behaviour. That split decided most of the architecture that followed.</p><h3>Cancel your tile requests</h3><p>Here’s the smallest change with the biggest effect on a bad connection, and it’s one line.</p><p>When a user pans across a country, every intermediate viewport queues a screenful of tiles. By the time they stop, dozens of requests are in flight for tiles nobody will ever look at — competing for the same few kilobits per second as the tiles they <em>are</em> looking at.</p><p>flutter_map has a provider that cancels them:</p><pre>TileLayer get openStreetMapTileLayer =&gt; TileLayer( urlTemplate: &#39;https://tile.openstreetmap.org/{z}/{x}/{y}.png&#39;, userAgentPackageName: &#39;np.gov.dor.dor&#39;, // Cancels in-flight requests for tiles that have scrolled out of view. // On a good connection this is a small optimisation; on one bar it is // the difference between the map filling in and the map hanging. tileProvider: CancellableNetworkTileProvider(), );</pre><p>On office wifi you won’t notice. On a mountain road you very much will.</p><p>Two things in that snippet that aren’t optional:</p><p><strong>userAgentPackageName is required, not decorative.</strong> OSM&#39;s tile usage policy requires a User-Agent identifying your app. The default flutter_map sends is a placeholder, and a placeholder is how you get blocked.</p><p><strong>Don’t use </strong><strong>{s} subdomains.</strong> You&#39;ll see https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png with subdomains: [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;] in most examples. OSM has deprecated that scheme - modern HTTP/2 makes parallel subdomains pointless, and their docs now ask you to hit tile.openstreetmap.org directly. Copying an old example is how it survives in codebases.</p><p>And the bigger version of that point: <strong>OSM’s public tile servers are a donation, not a CDN.</strong> They are explicitly not for heavy use. If your app is going to have real users, budget for your own tile server or a paid provider. Getting cut off after launch is a bad way to discover the policy.</p><h3>WMS: let the library do the bbox</h3><p>Government geospatial data mostly arrives as <strong>WMS</strong> — Web Map Service. You send a bounding box, it renders you an image.</p><p>I’ve hand-rolled the slippy-tile-to-bounding-box conversion before, and it’s a rite of passage with two classic bugs: tile rows count <em>downward</em> from the north pole while bounding boxes count <em>upward</em> from the south, and WMS 1.3.0 swapped the axis order for EPSG:4326 relative to 1.1.1. Get either wrong and your overlay is flipped or transposed — which on a symmetrical-looking river basin you will not notice until someone in the field does.</p><p>You mostly don’t have to. flutter_map computes it from the tile grid for you:</p><pre>TileLayer get hazardWmsLayer =&gt; TileLayer( wmsOptions: WMSTileLayerOptions( baseUrl: &#39;https://your-agency.gov.np/geoserver/ows?&#39;, layers: const [&#39;hazard:road_closures&#39;], format: &#39;image/png&#39;, transparent: true, // without this it paints over the base map ), userAgentPackageName: &#39;np.gov.dor.dor&#39;, tileProvider: CancellableNetworkTileProvider(), );</pre><p>Requesting on the standard z/x/y grid rather than the raw viewport is also what makes the responses cacheable: the same tile is the same URL for every user, instead of a new bbox on every pan. Ask a server admin how they feel about the alternative.</p><blockquote><strong><em>Check your own repo for this one.</em></strong><em> Mine had a WMS layer still pointing at </em><em>demo.boundlessgeo.com with </em><em>nasa:bluemarble and the </em><em>dev.fleaflet.flutter_map.example user agent - copied from the package example and never swapped out. It&#39;s the kind of thing that works in development and quietly ships.</em></blockquote><h3>The forecast is not your data</h3><p>Hazard warnings are built on external feeds — flood guidance and rainfall forecasts produced well outside the app. Three properties you have to design around:</p><ol><li><strong>They update on their schedule, not yours.</strong> A model run lands when it lands.</li><li><strong>They sometimes don’t land at all.</strong> A missed run is normal operations, not an outage.</li><li><strong>They are authoritative.</strong> You don’t get to interpolate, smooth, or “fix” a government hazard value because it looks odd.</li></ol><p>The third is a discipline thing and it’s the one I’d emphasise. It’s very tempting to average two grid cells for a nicer-looking map. Don’t. If an agency issues a value, the app shows that value. Presentation, not opinion.</p><p>What you <em>can</em> do is be honest about age:</p><pre>sealed class HazardState { const HazardState(); } class HazardFresh extends HazardState { const HazardFresh(this.data, this.issuedAt); final HazardLayer data; final DateTime issuedAt; } class HazardStale extends HazardState { const HazardStale(this.data, this.issuedAt); final HazardLayer data; final DateTime issuedAt; } class HazardUnavailable extends HazardState { const HazardUnavailable(this.lastKnown, this.reason); final HazardLayer? lastKnown; final String reason; }</pre><p>Three states, and the middle one is the important one. A four-hour-old flood layer is still useful — it is <em>not</em> the same as a current one, and the user is entitled to know which they’re looking at. “Updated 4 hours ago” in the corner of the map is a one-line change that does more for trust than any amount of polish.</p><h3>Offline is not a bonus feature here</h3><p>The users are on mountain roads. That’s the point of the app, and it’s exactly where connectivity fails.</p><ul><li><strong>Base tiles for the working region are pre-seeded</strong>, not fetched on demand. A bounded box at bounded zooms is a known quantity you can download once on wifi.</li><li><strong>The last good hazard layer is persisted</strong> and shown with its timestamp and a clear stale marker. An old map with an honest label beats a grey rectangle.</li><li><strong>Advisory text lives in a local database</strong>, because it’s small, it’s the part people actually read, and it should survive a cold start with no signal.</li><li><strong>Nothing retries in a tight loop.</strong> A device with no signal retrying every 5 seconds is a device with no battery by lunchtime.</li></ul><p>Same argument I made about <a href="https://hemnath.com.np/blog/offline-first">offline-first sync</a>, with one difference: the data here isn’t the user’s own work, so there’s no queue to drain. Read-only makes it simpler; time-critical makes it harder.</p><h3>Rendering: readable at a glance</h3><p>Small, but load-bearing. Hazard maps are read quickly, under stress, often outdoors in sunlight.</p><ul><li><strong>Colour is never the only signal.</strong> Severity gets a shape or an icon too — around 1 in 12 men has some colour-vision deficiency, and red-on-green is the worst possible pair to depend on.</li><li><strong>Three severity levels, not seven.</strong> Users act on “pass / careful / don’t”. A scale with more rungs than actions produces hesitation, not precision.</li><li><strong>The legend is on the map</strong>, not behind an info button. If it needs a tap, it isn’t there when it matters.</li></ul><h3>What I’d tell someone starting this</h3><p>Use the library’s WMS support rather than hand-rolling the bbox, set a real user agent, and don’t build on OSM’s public tiles if you expect real traffic.</p><p>Then decide, on paper, what the app shows when the data is four hours old and when it’s missing entirely. Those two states are most of the actual work, and they’re the ones that get designed last if you let them.</p><p>The map is the easy part.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/maps-and-weather-data/"><em>https://hemnath.com.np</em></a><em> on May 12, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0c5d07a6be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Flood Warning Is Just a Map Tile With a Deadline]]></title>
            <link>https://medium.com/@upretyhemnath/a-flood-warning-is-just-a-map-tile-with-a-deadline-bce06318be0c?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce06318be0c</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Tue, 12 May 2026 00:00:08 GMT</pubDate>
            <atom:updated>2026-08-10T10:20:52.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*94usK5CakK1XgeGI.jpg" /></figure><p>The hardest thing about building a road-hazard app was never the map.</p><p>Dropping a pin with flutter_map is a tutorial. What took the work was everything around it: rainfall forecasts arriving from a European model on their own schedule, flood guidance from a regional system in a format nobody designed for phones, a government map server that answers in 400ms on a good day, and a user standing at a road junction at 6am who needs to know one thing - <em>can I drive this or not?</em></p><p>This post is about the layer between a data source you don’t control and a screen that has to be right.</p><h3>Two kinds of layer, and why it matters</h3><p>Almost every mapping mistake I’ve made came from not separating these.</p><p><strong>Base tiles</strong> are the world: roads, rivers, contours. They change roughly never. OpenStreetMap raster tiles at zoom 6–14 for a country the size of Nepal is a bounded, cacheable quantity.</p><p><strong>Hazard layers</strong> are the news: which bridge is out, where flood guidance is red, where rainfall is forecast past a threshold. They change hourly and they’re worthless stale.</p><p>Treat both as “the map” and you get the worst of each — you re-download roads that haven’t moved since 2019, and you cache a flood warning until it’s a lie. Different fetch strategy, different cache lifetime, different failure behaviour. That split decided most of the architecture that followed.</p><h3>Cancel your tile requests</h3><p>Here’s the smallest change with the biggest effect on a bad connection, and it’s one line.</p><p>When a user pans across a country, every intermediate viewport queues a screenful of tiles. By the time they stop, dozens of requests are in flight for tiles nobody will ever look at — competing for the same few kilobits per second as the tiles they <em>are</em> looking at.</p><p>flutter_map has a provider that cancels them:</p><pre>TileLayer get openStreetMapTileLayer =&gt; TileLayer( urlTemplate: &#39;https://tile.openstreetmap.org/{z}/{x}/{y}.png&#39;, userAgentPackageName: &#39;np.gov.dor.dor&#39;, // Cancels in-flight requests for tiles that have scrolled out of view. // On a good connection this is a small optimisation; on one bar it is // the difference between the map filling in and the map hanging. tileProvider: CancellableNetworkTileProvider(), );</pre><p>On office wifi you won’t notice. On a mountain road you very much will.</p><p>Two things in that snippet that aren’t optional:</p><p><strong>userAgentPackageName is required, not decorative.</strong> OSM&#39;s tile usage policy requires a User-Agent identifying your app. The default flutter_map sends is a placeholder, and a placeholder is how you get blocked.</p><p><strong>Don’t use </strong><strong>{s} subdomains.</strong> You&#39;ll see https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png with subdomains: [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;] in most examples. OSM has deprecated that scheme - modern HTTP/2 makes parallel subdomains pointless, and their docs now ask you to hit tile.openstreetmap.org directly. Copying an old example is how it survives in codebases.</p><p>And the bigger version of that point: <strong>OSM’s public tile servers are a donation, not a CDN.</strong> They are explicitly not for heavy use. If your app is going to have real users, budget for your own tile server or a paid provider. Getting cut off after launch is a bad way to discover the policy.</p><h3>WMS: let the library do the bbox</h3><p>Government geospatial data mostly arrives as <strong>WMS</strong> — Web Map Service. You send a bounding box, it renders you an image.</p><p>I’ve hand-rolled the slippy-tile-to-bounding-box conversion before, and it’s a rite of passage with two classic bugs: tile rows count <em>downward</em> from the north pole while bounding boxes count <em>upward</em> from the south, and WMS 1.3.0 swapped the axis order for EPSG:4326 relative to 1.1.1. Get either wrong and your overlay is flipped or transposed — which on a symmetrical-looking river basin you will not notice until someone in the field does.</p><p>You mostly don’t have to. flutter_map computes it from the tile grid for you:</p><pre>TileLayer get hazardWmsLayer =&gt; TileLayer( wmsOptions: WMSTileLayerOptions( baseUrl: &#39;https://your-agency.gov.np/geoserver/ows?&#39;, layers: const [&#39;hazard:road_closures&#39;], format: &#39;image/png&#39;, transparent: true, // without this it paints over the base map ), userAgentPackageName: &#39;np.gov.dor.dor&#39;, tileProvider: CancellableNetworkTileProvider(), );</pre><p>Requesting on the standard z/x/y grid rather than the raw viewport is also what makes the responses cacheable: the same tile is the same URL for every user, instead of a new bbox on every pan. Ask a server admin how they feel about the alternative.</p><blockquote><strong><em>Check your own repo for this one.</em></strong><em> Mine had a WMS layer still pointing at </em><em>demo.boundlessgeo.com with </em><em>nasa:bluemarble and the </em><em>dev.fleaflet.flutter_map.example user agent - copied from the package example and never swapped out. It&#39;s the kind of thing that works in development and quietly ships.</em></blockquote><h3>The forecast is not your data</h3><p>Hazard warnings are built on external feeds — flood guidance and rainfall forecasts produced well outside the app. Three properties you have to design around:</p><ol><li><strong>They update on their schedule, not yours.</strong> A model run lands when it lands.</li><li><strong>They sometimes don’t land at all.</strong> A missed run is normal operations, not an outage.</li><li><strong>They are authoritative.</strong> You don’t get to interpolate, smooth, or “fix” a government hazard value because it looks odd.</li></ol><p>The third is a discipline thing and it’s the one I’d emphasise. It’s very tempting to average two grid cells for a nicer-looking map. Don’t. If an agency issues a value, the app shows that value. Presentation, not opinion.</p><p>What you <em>can</em> do is be honest about age:</p><pre>sealed class HazardState { const HazardState(); } class HazardFresh extends HazardState { const HazardFresh(this.data, this.issuedAt); final HazardLayer data; final DateTime issuedAt; } class HazardStale extends HazardState { const HazardStale(this.data, this.issuedAt); final HazardLayer data; final DateTime issuedAt; } class HazardUnavailable extends HazardState { const HazardUnavailable(this.lastKnown, this.reason); final HazardLayer? lastKnown; final String reason; }</pre><p>Three states, and the middle one is the important one. A four-hour-old flood layer is still useful — it is <em>not</em> the same as a current one, and the user is entitled to know which they’re looking at. “Updated 4 hours ago” in the corner of the map is a one-line change that does more for trust than any amount of polish.</p><h3>Offline is not a bonus feature here</h3><p>The users are on mountain roads. That’s the point of the app, and it’s exactly where connectivity fails.</p><ul><li><strong>Base tiles for the working region are pre-seeded</strong>, not fetched on demand. A bounded box at bounded zooms is a known quantity you can download once on wifi.</li><li><strong>The last good hazard layer is persisted</strong> and shown with its timestamp and a clear stale marker. An old map with an honest label beats a grey rectangle.</li><li><strong>Advisory text lives in a local database</strong>, because it’s small, it’s the part people actually read, and it should survive a cold start with no signal.</li><li><strong>Nothing retries in a tight loop.</strong> A device with no signal retrying every 5 seconds is a device with no battery by lunchtime.</li></ul><p>Same argument I made about <a href="https://hemnath.com.np/blog/offline-first">offline-first sync</a>, with one difference: the data here isn’t the user’s own work, so there’s no queue to drain. Read-only makes it simpler; time-critical makes it harder.</p><h3>Rendering: readable at a glance</h3><p>Small, but load-bearing. Hazard maps are read quickly, under stress, often outdoors in sunlight.</p><ul><li><strong>Colour is never the only signal.</strong> Severity gets a shape or an icon too — around 1 in 12 men has some colour-vision deficiency, and red-on-green is the worst possible pair to depend on.</li><li><strong>Three severity levels, not seven.</strong> Users act on “pass / careful / don’t”. A scale with more rungs than actions produces hesitation, not precision.</li><li><strong>The legend is on the map</strong>, not behind an info button. If it needs a tap, it isn’t there when it matters.</li></ul><h3>What I’d tell someone starting this</h3><p>Use the library’s WMS support rather than hand-rolling the bbox, set a real user agent, and don’t build on OSM’s public tiles if you expect real traffic.</p><p>Then decide, on paper, what the app shows when the data is four hours old and when it’s missing entirely. Those two states are most of the actual work, and they’re the ones that get designed last if you let them.</p><p>The map is the easy part.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/maps-and-weather-data/"><em>https://hemnath.com.np</em></a><em> on May 12, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce06318be0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Shipped a Boolean. Here’s the Sync Layer I’d Build Now.]]></title>
            <link>https://medium.com/@upretyhemnath/i-shipped-a-boolean-heres-the-sync-layer-i-d-build-now-267847db10f4?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/267847db10f4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 00:00:38 GMT</pubDate>
            <atom:updated>2026-08-10T10:18:50.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZiJnoRkoI4pf67Sx.jpg" /></figure><p>An auditor for a Swiss fair-trade certifier drives out to a carpet weaving workshop in rural Nepal. The road is bad. The last cell tower was forty minutes back. They spend the next six hours walking the looms, interviewing weavers about hours and pay, photographing the workshop floor, and filling in a hundred-question audit form on a tablet.</p><p>Then they drive home and the form has to be in the system.</p><p>I built that app. It worked, it shipped, auditors used it in the field for years. And the core of its sync layer was a single boolean column called syncStatus.</p><p>That decision was fine. It was also the thing I’d change first, and the reasons why are most of what I know about offline-first.</p><h3>What “offline-first” actually demands</h3><p>The reframe that matters: <strong>your app talks to a local database. Something else talks to the server.</strong></p><p>If any user-facing action calls the API directly and waits for the response, you don’t have an offline-first app. You have an online app with error handling. The difference shows up the first time someone taps “Save” on one bar and watches a spinner for thirty seconds.</p><blockquote><em>No screen ever awaits a network call to complete a user action.</em></blockquote><p>Save writes locally and returns immediately. Whether that record has reached the cloud is a separate concern, owned by a separate part of the app. That part was right in the app I shipped, and it’s the part I’d keep unchanged.</p><h3>The dirty flag, and what it cost</h3><p>Here’s the design I actually used. Every record carries a flag:</p><pre>@Entity data class Audit( @PrimaryKey val id: Long, // ... val syncStatus: Boolean = false, // false = needs uploading )</pre><p>A background worker queries WHERE syncStatus = 0, uploads each row, and flips the flag on success. It&#39;s about as simple as sync gets, and for a while that simplicity is a genuine feature.</p><p>Four things it cannot express, in the order they bit me:</p><p><strong>1. Why an upload failed.</strong> A boolean has room for “done” and “not done”. It has no room for <em>“the server rejected this because section 4 is incomplete”</em> versus <em>“there was no signal.”</em> Both stay false, and both get retried forever - so one malformed record retries on every sync cycle for weeks, quietly, while the user is told nothing.</p><p><strong>2. How many times you’ve tried.</strong> No attempt count means no backoff and no giving up. A record the server will never accept is indistinguishable from one you haven’t reached yet.</p><p><strong>3. Ordering.</strong> Rows come back in whatever order the query returns. If a corrective action references an audit that hasn’t uploaded yet, you find out from a foreign-key error on the server.</p><p><strong>4. Deletes.</strong> A deleted row has no flag, because it has no row. Deletions need a separate mechanism, which means the “one simple boolean” was never actually one mechanism.</p><p>None of these were emergencies. All of them were papered over with special cases, and the special cases are what made the sync code hard to change.</p><h3>The outbox, which is what I’d build now</h3><p>Instead of marking records, record the <em>intent</em>. Every mutation goes into a table of pending operations, and a worker drains it:</p><pre>@Entity(tableName = &quot;outbox&quot;) data class OutboxEntry( @PrimaryKey val id: String, // client-generated UUID val endpoint: String, val payload: String, // serialized body val createdAt: Long, val attempts: Int = 0, val lastError: String? = null, ) @Dao interface OutboxDao { @Insert suspend fun enqueue(entry: OutboxEntry) @Query(&quot;SELECT * FROM outbox ORDER BY createdAt ASC LIMIT 20&quot;) suspend fun nextBatch(): List&lt;OutboxEntry&gt; @Query(&quot;DELETE FROM outbox WHERE id = :id&quot;) suspend fun remove(id: String) }</pre><p>Look at what those four extra columns buy: createdAt gives you ordering, attempts gives you backoff, lastError gives you something to show the user, and a row per <em>operation</em> rather than per <em>record</em> means deletes are just another entry.</p><p>Saving becomes two local writes in one transaction — the record, and the intent to sync it:</p><pre>suspend fun saveAudit(audit: Audit) = db.withTransaction { auditDao.upsert(audit.copy(syncState = SyncState.PENDING)) outboxDao.enqueue( OutboxEntry( id = audit.id, // same id, deliberately endpoint = &quot;/audits&quot;, payload = json.encodeToString(audit), createdAt = System.currentTimeMillis(), ) ) }</pre><p>And the worker gets three outcomes instead of two:</p><pre>class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { override suspend fun doWork(): Result { val batch = outboxDao.nextBatch() for (entry in batch) { when (val outcome = push(entry)) { is Pushed -&gt; outboxDao.remove(entry.id) is Retryable -&gt; return Result.retry() // backoff, keep order is Rejected -&gt; quarantine(entry, outcome.reason) } } return Result.success() } }</pre><p><strong>Three outcomes, not two — this is the fix for problem one.</strong> A validation error is <em>permanent</em>: it must leave the queue, get flagged, and surface to the user. A timeout is <em>temporary</em>: back off and retry. Collapsing those into “failed” is exactly what a boolean forces you to do.</p><p>Schedule against connectivity rather than a timer:</p><pre>val request = PeriodicWorkRequestBuilder&lt;SyncWorker&gt;(15, TimeUnit.MINUTES) .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() ) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build()</pre><p>The shape is identical in Flutter — a Drift or sqflite table, connectivity_plus to wake the drain:</p><pre>Future&lt;void&gt; saveAudit(Audit audit) async { await db.transaction(() async { await auditDao.upsert(audit.copyWith(syncState: SyncState.pending)); await outboxDao.enqueue(OutboxEntry( id: audit.id, endpoint: &#39;/audits&#39;, payload: jsonEncode(audit), createdAt: DateTime.now().millisecondsSinceEpoch, )); }); unawaited(syncer.drain()); // fire and forget - the UI has already moved on }</pre><p>unawaited is doing real work there. The user&#39;s tap completed the moment the transaction committed.</p><h3>Client-generated IDs</h3><p>The classic offline bug: the request succeeded, the response never arrived, the client retried, and now there are two audits.</p><p>You cannot prevent this from the client. Networks fail between “server committed” and “client heard about it.” What you <em>can</em> do is make the duplicate harmless — generate the ID on the device and send it as an idempotency key:</p><pre>val response = api.submitAudit( idempotencyKey = entry.id, body = entry.payload, )</pre><p>A retried request lands on the same row. The second write is a no-op.</p><p>This needs backend agreement, and it’s worth raising in week one. Retrofitting deduplication onto production data costs considerably more than designing it in.</p><h3>The part nobody warns you about: images</h3><p>Every offline-first post stops at JSON. The field app’s hardest sync problem was photographs.</p><p>A hundred-question audit comes with dozens of images of the workshop, certificates and equipment. They are two orders of magnitude larger than the form, they upload as multipart rather than JSON, and a 4G handover mid-upload means starting that file again.</p><p>What I’d do differently:</p><ul><li><strong>Queue images as separate outbox entries</strong>, not as part of the audit payload. One 8 MB photo failing shouldn’t block a 30 KB form.</li><li><strong>Upload images first, reference them by ID.</strong> Then the form submission is small and atomic.</li><li><strong>Downscale on device before queueing.</strong> A 12-megapixel photo of a paper certificate is a data bill, not evidence.</li><li><strong>Chunk large uploads,</strong> so a dropped connection costs you a chunk rather than a file.</li></ul><p>Every one of those is a lesson from watching the simple version fail on a mountain road.</p><h3>Sync goes both ways</h3><p>The other thing the outbox alone doesn’t cover: the server has news too. Audit schedules get assigned, supplier records change, someone’s assignment moves.</p><p>That’s a genuinely separate mechanism — a pull, driven by a cursor or a timestamp, reconciling server state into the local database. Push and pull share a trigger and almost nothing else, and trying to unify them produced the most confusing code in the original app.</p><p>Which raises the question the pull creates: <strong>what happens when both sides changed?</strong></p><h3>“Last write wins” is a decision</h3><p>Two auditors edit the same supplier. One is in the field and syncs at 6pm. One edited from the office at 2pm but only reconnected at 6:05pm.</p><p>There’s no universally correct answer, and that’s the point — the failure isn’t picking the wrong strategy, it’s picking one <em>accidentally</em> by writing PUT /supplier/123 and never thinking about it. That silently means last request to arrive wins, which isn&#39;t even last edit wins. It&#39;s whoever&#39;s network recovered most recently.</p><ul><li><strong>Last write wins by client timestamp.</strong> Cheap. Fine for single-owner records. Watch out: device clocks are wrong more often than you’d like.</li><li><strong>Server wins.</strong> Also cheap, and honest about it. Good for reference data.</li><li><strong>Field-level merge.</strong> Two people editing different fields both keep their changes. More work, usually right for forms.</li><li><strong>Flag it and ask a human.</strong> Necessary when quietly discarding an edit isn’t acceptable.</li></ul><p>The important part isn’t which you choose. It’s that it was a decision, rather than an emergent property of a REST verb.</p><h3>Error states that name the failure</h3><p>The least technical section, and the one that moved user trust most.</p><p>“Something went wrong” is not an error message. It’s an apology for not having written one. The user’s question is always <em>do I need to do something?</em></p><p>They all say where the data is and whether the user must act. Note that the third one is only writable <em>because</em> the outbox stored lastError - with a boolean, the honest message is &quot;something failed,&quot; which is the message I actually shipped.</p><p>The auditors were never thinking about my sync queue. They were thinking about whether six hours of work still existed. The interface’s only job was to answer that, continuously, without being asked.</p><h3>What I’d tell someone starting today</h3><p><strong>Build the sync layer first.</strong> Retrofitting offline into a working online app means touching every repository and most screens. The other direction is easy: an offline-first app on a fast connection just syncs immediately.</p><p><strong>Make the queue visible in-app from day one.</strong> A hidden debug screen listing pending items, attempt counts and last errors. It has resolved more “the app lost my data” reports than any logging I’ve set up — usually the data was right there, waiting on an expired token.</p><p><strong>Test on airplane mode, then on something worse.</strong> Airplane mode is a clean binary. Real failure is one bar, eight seconds of latency, and a drop mid-upload.</p><p><strong>Ask the backend team for idempotency keys before you write a line of client code.</strong></p><p>None of this is novel. Outboxes and idempotency keys are decades old. What changed for me was the order of operations: connectivity stopped being a happy path with a fallback, and became the thing the design was shaped around from the first commit.</p><p>The boolean shipped. It just made every subsequent question harder to answer than it needed to be.</p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/offline-first/"><em>https://hemnath.com.np</em></a><em> on April 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267847db10f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Rule That Depends on Someone Noticing Isn’t a Rule]]></title>
            <link>https://medium.com/@upretyhemnath/a-rule-that-depends-on-someone-noticing-isnt-a-rule-8f10c7729967?source=rss-312b8bf967f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f10c7729967</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[app-architecture]]></category>
            <dc:creator><![CDATA[Upretyhemnath]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 00:00:31 GMT</pubDate>
            <atom:updated>2026-08-10T11:03:46.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MEp5hZdJzziC1IMl.jpg" /></figure><p>Every Android codebase I’ve joined has had a data package, a domain package, and a ui package. Most of them also had a ViewModel calling Retrofit directly, somewhere, put there at 6pm before a release.</p><p>Nobody was being careless. The architecture was just never enforced by anything. ui importing data is legal Kotlin. The rule lived in a README and in whoever happened to review the PR - and a rule that depends on someone noticing is not a rule, it&#39;s a hope.</p><p>So I stopped writing the rule down and started making the compiler hold it. The result is <a href="https://github.com/hemnathuprety/AppArchitecture">AppArchitecture</a> — a multi-module Android template that boots to a working demo flow. The login, signup and dashboard screens are there to prove the wiring holds end to end, not because the template is about authentication. This post walks through why it’s split the way it is.</p><h3>The graph is the architecture</h3><p>Here’s the entire settings.gradle.kts:</p><pre>rootProject.name = &quot;App Architecture&quot; include(&quot;:app&quot;) include(&quot;:core-ui&quot;) include(&quot;:feature-model&quot;) include(&quot;:core-data&quot;) include(&quot;:core-database&quot;) include(&quot;:app-testing&quot;) include(&quot;:core-testing&quot;)</pre><p>And here’s what actually matters — who is allowed to see whom:</p><pre>app ──────────────► core-ui └────────────────► feature-model ├──────────► core-ui └──────────► core-data └────────► core-database app-testing ──────► (everything, test-only) core-testing (leaf: Hilt test runner)</pre><p>Read the top line again: <strong>app does not depend on </strong><strong>core-data.</strong> There is no implementation(project(&quot;:core-data&quot;)) in app/build.gradle.kts. That means MainActivity cannot import AuthRepository. Not &quot;shouldn&#39;t&quot; - <em>cannot</em>. The symbol isn&#39;t on its compile classpath. Try it and Gradle stops the build before a reviewer ever sees the diff.</p><p>That’s the whole argument for modules over packages, and it’s worth being precise about it: <strong>packages organise code; modules constrain it.</strong> A package boundary is a naming convention. A module boundary is a compiler-enforced contract with a build failure attached.</p><p>The same holds one level down. core-data depends on core-database, but never the reverse - so the Room layer cannot reach back up and start making HTTP calls. The arrow only points one way, and Gradle rejects a cycle outright.</p><h3>What each module owns</h3><p>core-ui and core-database are leaves - nothing about them can drag the rest of the graph in. That&#39;s what keeps incremental builds from recompiling the world when you change a colour.</p><h3>One call, all the way down</h3><p>Abstract layer diagrams are easy to agree with and hard to learn from. Here’s the actual path a tap takes.</p><p><strong>A result type that has three states, not two.</strong> Loading is a real state, not the absence of a result:</p><pre>sealed class Resource&lt;T&gt;( val data: T? = null, val message: String? = null, ) { class Success&lt;T&gt;(data: T): Resource&lt;T&gt;(data) class Error&lt;T&gt;(message: String, data: T? = null): Resource&lt;T&gt;(data, message) class Loading&lt;T&gt;(data: T? = null): Resource&lt;T&gt;(data) }</pre><p><strong>The repository is boring on purpose.</strong> It talks to Retrofit and returns. No caching decisions, no error interpretation, no business logic:</p><pre>class AuthRepository @Inject constructor( private val apIs: AuthAPIs ) { suspend fun login(request: LoginRequest): Response&lt;LoginResponse&gt; { return apIs.login(request) } }</pre><p>People often ask what a repository is <em>for</em> when it looks like this. It’s for being the only thing in the codebase that knows Retrofit exists. Swap to Ktor and exactly one file changes.</p><p><strong>The use case is where the work happens</strong> — call the API, interpret the response, persist the session, and emit each stage as a Flow:</p><pre>class AuthUseCase @Inject constructor( private val dao: UserAuthDao, private val authRepository: AuthRepository ) { operator fun invoke(request: LoginRequest) = flow { try { emit(Resource.Loading()) val apiResponse = authRepository.login(request) if (apiResponse.isSuccessful) { val result = apiResponse.body() as LoginResponse dao.nukeTable() dao.insertUserInfo(result.toUserAuthDBModel()) emit(Resource.Success(&quot;Login Successful!&quot;)) } else { val errorMessage = resolveError(apiResponse.code(), apiResponse.errorBody()) emit(Resource.Error(errorMessage.message, errorMessage.isUnAuthorize)) } } catch (e: Exception) { emit(Resource.Error(handelException(e))) } } }</pre><p>Note operator fun invoke. The use case is called as authUseCase(request) - it reads as a verb, which is what it is. One class, one job.</p><p>Note also the try/catch wrapping the whole flow. A dropped connection throws rather than returning an unsuccessful response, and if you only handle isSuccessful == false you get a crash instead of an error state. Two different failure paths, both of which have to end somewhere the UI can render.</p><p><strong>The ViewModel translates </strong><strong>Resource into something a screen can render</strong>, and never sees Retrofit or Room:</p><pre>data class BaseUiState&lt;T&gt;( val isLoading: Boolean = false, val hasError: Boolean = false, val hasSuccess: Boolean = false, val errorMessage: String = &quot;&quot;, val errorType: String = &quot;api&quot;, val data: T? = null )</pre><pre>@HiltViewModel class LoginViewModel @Inject constructor( private val authUseCase: AuthUseCase ) : ViewModel() { private var _loginState = MutableStateFlow(BaseUiState&lt;String&gt;()) val loginState: StateFlow&lt;BaseUiState&lt;String&gt;&gt; = _loginState fun login(username: String, password: String) { viewModelScope.launch { authUseCase.invoke(LoginRequest(username, password)).collect { resource -&gt; when (resource) { is Resource.Loading -&gt; _loginState.value = BaseUiState(isLoading = true) is Resource.Success -&gt; _loginState.value = BaseUiState(data = resource.data as? String, hasSuccess = true) is Resource.Error -&gt; _loginState.value = BaseUiState(hasError = true, errorMessage = resource.message ?: &quot;&quot;) } } } } }</pre><p>_loginState is private and mutable; loginState is public and read-only. The screen can observe but never assign - the same one-way constraint as the module graph, applied to state.</p><p>The errorType field on BaseUiState exists so the screen can tell <em>which</em> field to highlight. Empty username sets errorType = &quot;username_empty&quot; without any network call at all. &quot;Invalid input&quot; and &quot;the server said no&quot; look identical in a naive UI state, and they need different handling - one focuses a text field, the other shows a dialog.</p><h3>Tests live in their own module</h3><p>This is the part I’d defend hardest, and the least common.</p><p>app-testing uses the com.android.test plugin - a Gradle module whose only output is instrumentation tests. It depends on every production module; nothing depends on it. Fakes and test doubles go there:</p><pre>app-testing/src/main/java/com/hemnath/apptesting/testdi/TestDatabaseModule.kt core-testing/src/main/java/com/hemnath/testing/HiltTestRunner.kt</pre><p>TestDatabaseModule swaps the real Room database for an in-memory one through Hilt. The test asks for UserAuthDao exactly as production code does, and gets a fake - because the DI graph, not the calling code, decides what &quot;the database&quot; means. No if (BuildConfig.DEBUG) anywhere.</p><p>Keeping this in its own module means test-only dependencies never enter the production classpath, and a broken fake can’t compile its way into a release build.</p><h3>The customizer script</h3><p>A template nobody can start from is just a repo you read once. Cloning this one and renaming com.hemnath.architecture_cm by hand across seven modules is exactly the kind of chore that ends with a stale package name in three files.</p><p>So it’s one command:</p><pre>./customizer.sh your.package.name DataItemType MyApplication</pre><p>That rewrites the package across every module and renames the sample entity, screen and exposed state to your domain type. Two minutes instead of an afternoon.</p><h3>When not to do this</h3><p>Seven modules for an app this small is, on its face, absurd. I’d say so plainly.</p><p>The cost is real: more Gradle files, slower clean builds, and a genuine learning curve for anyone joining. If you’re building a three-screen app alone and shipping next month, a single module with disciplined packages will serve you better, and you’ll know when it stops doing so.</p><p>Where this pays for itself is the case it was built for — several people in the codebase at once, a project measured in years, and features that arrive as whole verticals. Then the module graph does work no convention can: it makes the wrong import impossible instead of merely discouraged, and it stops one team’s change from recompiling another’s.</p><p>I’ve since built several production apps on this split, which is the only reason I’d recommend it. A structure that survives one project is a preference; one that survives several, under deadlines, with other people in it, is a default.</p><p>The template exists because I kept rebuilding this by hand at the start of every project, and rebuilding it by hand is how details get dropped.</p><p>Clone it, run the script, delete what you don’t need: <a href="https://github.com/hemnathuprety/AppArchitecture"><strong>github.com/hemnathuprety/AppArchitecture</strong></a></p><p><em>I build mobile apps — eleven years of it, mostly Android in Kotlin, and more recently Flutter and Kotlin Multiplatform. A lot of that work has been offline-first tools for public agencies and development organisations in Nepal. If you’re building something in this space, I’d like to hear about it: </em><a href="https://hemnath.com.np/"><em>hemnath.com.np</em></a> <a href="https://hemnath.com.np/#contact">Get in touch</a></p><p><em>Originally published at </em><a href="https://hemnath.com.np/blog/clean-architecture/"><em>https://hemnath.com.np</em></a><em> on April 13, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f10c7729967" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>