<?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 Majidshahbaz on Medium]]></title>
        <description><![CDATA[Stories by Majidshahbaz on Medium]]></description>
        <link>https://medium.com/@majidshahbaz75?source=rss-394ad2b31423------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0zWeGWTgqSRP8XZ6Dic1xQ.jpeg</url>
            <title>Stories by Majidshahbaz on Medium</title>
            <link>https://medium.com/@majidshahbaz75?source=rss-394ad2b31423------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:25:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majidshahbaz75/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[I Counted Every Hidden Channel Kotlin Flow Creates — Most Devs Are Wrong About Which Operators Are…]]></title>
            <link>https://proandroiddev.com/i-counted-every-hidden-channel-kotlin-flow-creates-most-devs-are-wrong-about-which-operators-are-8f38cf676e07?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f38cf676e07</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 05:43:19 GMT</pubDate>
            <atom:updated>2026-09-13T05:43:19.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMc4_1ZrUt-iiWyJVGgI9w.png" /><figcaption>Image Generated for the Article</figcaption></figure><h3>I Counted Every Hidden Channel Kotlin Flow Creates — Most Devs Are Wrong About Which Operators Are Free</h3><h4>buffer() and flowOn() are supposed to fuse into one channel when chained. I wrote code to prove it — and then found four &quot;harmless&quot; operators that quietly break it.</h4><p>Ask any experienced Kotlin developer what happens when you chain .buffer().flowOn(Dispatchers.IO).buffer(), and you&#39;ll usually get a confident answer: &quot;it fuses into one channel.&quot; That&#39;s the folklore, repeated in talks, docs, and Stack Overflow answers.</p><p>It’s also only half true, and nobody seems to have actually checked the other half: <strong>which everyday operators quietly stop that fusion from happening.</strong></p><p>I decided to stop trusting folklore and instrument the actual runtime. Five separate experiments later, I had a very clear, very measurable answer — and one of the results genuinely surprised me.</p><h3>The Myth, and the Mechanism Behind It</h3><p>Kotlin’s coroutines library really does fuse adjacent channelFlow, flowOn, buffer, and produceIn calls into a single underlying channel instead of creating one per operator. This isn&#39;t a rumor — it&#39;s real, deliberate behavior, implemented through an interface called FusibleFlow.</p><p>Here’s the actual check, straight from the source:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd3b407c1f2b2955b3df4be68ca18b5/href">https://medium.com/media/1cd3b407c1f2b2955b3df4be68ca18b5/href</a></iframe><p>When flowOn() or buffer() is called, it checks whether the flow it&#39;s being called on already implements FusibleFlow. If it does, instead of wrapping it in a new object, it calls .fuse() — which updates the <em>existing</em> object&#39;s settings (buffer size, dispatcher) in place. No new object. No new coroutine. No new channel.</p><p>But that check only succeeds if the upstream is <em>already</em> a ChannelFlow. And that&#39;s where the folklore quietly stops being true.</p><h3>Building Something to Actually Measure This</h3><p>I wrote two nearly identical pipelines — one where the fusible operators sit directly next to each other, and one where a completely ordinary map() sits in the middle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/045bd349ab5259895fa4edc0814298d1/href">https://medium.com/media/045bd349ab5259895fa4edc0814298d1/href</a></iframe><p>Nothing about the “broken” version looks dangerous. It’s the kind of line every Android developer writes without a second thought. That’s exactly the point.</p><h3>Proof 1: Counting the Wrapper Objects</h3><p>Every Flow that isn’t fused wraps its upstream in a new object — like a nesting doll. I wrote a small reflection-based function that walks the private upstream-flow reference inside these objects and counts how many layers deep it goes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cf1104cd111d12cf4be69ede680ff5/href">https://medium.com/media/20cf1104cd111d12cf4be69ede680ff5/href</a></iframe><p>Running this against both pipelines gave a clean, unambiguous result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38d5EQkWq6YlTMLdVBby_Q.png" /></figure><p>The fused chain is still, structurally, a single object — buffer size and dispatcher just got updated in place. The moment map() shows up, Kotlin has no choice but to build a second, separate wrapper on top of it.</p><h3>Proof 2: Watching It Happen at Runtime</h3><p>Object structure is one thing — but does it actually change how many coroutines exist while your code is running? I used kotlinx-coroutines-debug&#39;s live coroutine dump to check, mid-collection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99f99081dc4e00453a9670705138b91c/href">https://medium.com/media/99f99081dc4e00453a9670705138b91c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeVSPQNjvuh1LTTIPPmE0w.png" /><figcaption>Diagram generated for this article, built from real measured output.</figcaption></figure><p>The fused pipeline showed exactly <strong>2</strong> live coroutines: one collector, one producer. That’s the theoretical minimum — one of each.</p><p>The broken pipeline showed <strong>3</strong>: the collector, plus <em>two separate</em> producer coroutines. map() didn&#39;t just create an extra object — it created an entire extra coroutine, complete with its own internal channel and its own scheduling overhead, for a transform that does nothing more than multiply a number.</p><h3>Proof 3: The Real Thread-Hop Cost</h3><p>Extra coroutines are one kind of overhead. Extra thread hops are another, more directly tied to performance. I wrapped Dispatchers.IO and Dispatchers.Default in a custom dispatcher that logs every real dispatch call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dcdd6b5a52fe2c6741fd901163f2c90/href">https://medium.com/media/4dcdd6b5a52fe2c6741fd901163f2c90/href</a></iframe><p>The fused pipeline made exactly <strong>1</strong> real dispatcher hop. The broken pipeline — same operators, same intent, just map() sitting in a different place — made <strong>3</strong>. Three times the thread hand-offs, for code that reads almost identically.</p><h3>The Twist: Not Every “Ordinary” Operator Behaves the Same Way</h3><p>At this point, the obvious follow-up question is: is it just map(), or does <em>any</em> transform in the middle break fusion? I tested four operators that all look equally ordinary — catch(), onEach(), distinctUntilChanged(), and conflate():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67951d335bb25dff97670d954a8d95a5/href">https://medium.com/media/67951d335bb25dff97670d954a8d95a5/href</a></iframe><p>Here’s what came back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5o3hFPw9KKTmLuTB27frA.png" /></figure><p>Three operators most developers would assume are “lightweight” — a side-effect hook, an equality check, an error handler — all break fusion exactly like map() does.</p><p>conflate(), meanwhile, stays completely fused. That&#39;s not an accident: conflate() is literally implemented internally as buffer(capacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST). It <em>is</em> buffer(), wearing a different name. I confirmed this held even at the coroutine level — swapping map() for conflate() in the exact same position dropped the live coroutine count straight back down from 3 to 2.</p><h3>What This Actually Means for Your Code</h3><p>This isn’t an argument against using map(), catch(), onEach(), or distinctUntilChanged() — they&#39;re essential, and in most UI-layer Flow chains, one extra coroutine changes nothing anyone will notice.</p><p>It matters when you’re building something with real throughput — a high-frequency sensor pipeline, a large paginated data stream, a hot WebSocket feed — where every extra coroutine and every extra thread hop adds up. In those cases:</p><ul><li><strong>Group your fusible operators together.</strong> If you’re going to buffer() and flowOn(), do it adjacently, before or after your transforms — not sandwiched in between them.</li><li><strong>Don’t assume “simple-looking” means “free.”</strong> onEach {} and distinctUntilChanged() read like they should be nearly free. They aren&#39;t, in this specific sense.</li><li><strong>Reach for </strong><strong>conflate() over </strong><strong>buffer(0, DROP_OLDEST) when it fits your semantics</strong> — not because it&#39;s clearer (though it is), but because it&#39;s a genuine drop-in replacement for buffer() at the implementation level.</li></ul><h3>The Real Takeaway</h3><p>None of this changes what Flow is <em>for</em>. It changes what “the compiler/runtime will optimize this for me” actually covers. Fusion isn’t a blanket guarantee across your whole pipeline — it’s a narrow, specific mechanism that only fires between a small set of operators, and it silently steps aside the moment something else gets in the way.</p><p>The folklore (“buffer/flowOn fuse&quot;) is true. The unspoken assumption most of us carry alongside it — that <em>most</em> operators are basically free — isn&#39;t. The only way to know which side of that line a given operator sits on is to actually measure it, the same way we just did.</p><p><em>If this changed how you’ll write your next Flow pipeline, give it a clap 👏 — and if you’ve found another operator with a surprising fusion story, drop it in the comments. I’ll test it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f38cf676e07" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/i-counted-every-hidden-channel-kotlin-flow-creates-most-devs-are-wrong-about-which-operators-are-8f38cf676e07">I Counted Every Hidden Channel Kotlin Flow Creates — Most Devs Are Wrong About Which Operators Are…</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Gave My AI Agent Eyes Inside a Real Compose App]]></title>
            <link>https://proandroiddev.com/i-gave-my-ai-agent-eyes-inside-a-real-compose-app-e7d4546417f8?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7d4546417f8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 16:50:55 GMT</pubDate>
            <atom:updated>2026-08-30T16:50:55.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRQCDJSRpqP549mgGTAnNw.png" /><figcaption>Title Image generated By Author</figcaption></figure><p><strong>For years, AI coding agents have written Compose UI blind — they generate the code, then wait for you to run it, look at it, and report back. Compose Hot Reload’s new MCP server changes that math. I wired one up to a fresh Compose Multiplatform desktop app, handed the agent a bug I never described, and watched it find its own way to the fix.</strong></p><p>Picture this. You ask an AI agent to build you a small screen — a form, a list, a counter, whatever. It writes plausible-looking Compose code in about four seconds, tells you it’s done, and waits. You run the app. Something’s wrong: a button doesn’t respond, a list won’t update, text clips off the edge of the card. You paste a screenshot back. You describe what you’re seeing in words, because the agent has no eyes. It apologizes, guesses, tries again. Repeat.</p><p>Compose Hot Reload — the tool that already lets you edit a running Compose Desktop app without restarting it — now bundles an experimental MCP (Model Context Protocol) server. Point an MCP-aware agent at it, and instead of trading screenshots back and forth in chat, the agent gets direct tool calls into your actual running app:</p><p>That loop — write, run, describe, paste, guess — is the actual bottleneck in AI-assisted UI work right now, and it hasn’t gotten much attention because it isn’t a training problem. It’s a plumbing problem. The model was never given a way to look.</p><p>Compose Multiplatform 1.12.0 ships a first attempt at fixing that plumbing, and I wanted to see if it holds up outside a demo gif.</p><h3>What Actually Shipped</h3><p>Sixteen tools in total, but the ones that matter for a debugging loop are take_screenshot, get_semantic_tree, click, long_click, type_text, scroll, reload, and get_logs. status and get_ui_error round it out — the former tells the agent whether an app is even connected before it wastes a call, the latter surfaces a composable’s runtime exception directly instead of making the agent guess from a blank window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZjFCern8VQR1cdGG6yr_Q.png" /><figcaption>Image generated By Author</figcaption></figure><p>Wiring it up is supposed to be almost boring. Compose Hot Reload has shipped bundled-by-default since CMP 1.10.0 for any project with a desktop target, so there’s no separate plugin to add. You drop one file in the project root:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;compose-hot-reload&quot;: {<br>      &quot;command&quot;: &quot;./gradlew&quot;,<br>      &quot;args&quot;: [&quot;--no-daemon&quot;, &quot;--quiet&quot;, &quot;--console=plain&quot;, &quot;hotMcpServer&quot;]<br>    }<br>  }<br>}</pre><p><em>(Full file: </em><em>mcp.json </em><a href="https://gist.github.com/Majid460/3a0ae2233b5b20757fb7a2aa5d3e16a6"><em>gist</em></a><em>)</em></p><p>And that’s it, in theory. In practice, I hit three things worth knowing about before you try this yourself.</p><h3>Setting It Up: Three Real Walls</h3><p>I scaffolded a minimal Kotlin Multiplatform project — a composeApp module, a single jvm(“desktop”) target, two small screens, nothing fancy — and pointed it at Compose Multiplatform 1.12.0.</p><p><strong>Wall one: the Kotlin version.</strong> My gradle build failed immediately with Minimal supported Kotlin Gradle Plugin version is 2.2.0. I’d started from a slightly older known-good template pinned to Kotlin 2.1.21, which is fine for older Compose releases but not for 1.12.0. Bumping kotlin.version to 2.2.20 in the version catalog fixed it in one line.</p><p><strong>Wall two: run isn’t the task you want. </strong>I first launched the app with a plain ./gradlew run. It worked — window opened, counter incremented — but the MCP server’s status tool reported “connected”: false the entire time. The actual Compose Hot Reload run task is target-qualified: hotRunDesktop, not run. Once I killed the plain run and relaunched with ./gradlew hotRunDesktop, status flipped to “connected”: true immediately. This is exactly the target-name gotcha worth checking for in your own build.gradle.kts before you assume the wiring is broken — a desktopApp target would give you hotRunDesktopApp and hotMcpServerDesktopApp instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213eb28e89d039a7770d42694608cdc0/href">https://medium.com/media/213eb28e89d039a7770d42694608cdc0/href</a></iframe><p><strong>Wall three (a non-wall, worth naming anyway): the kotlin-logging stdout issue.</strong> There’s a known report of a stray kotlin-logging: initializing… line hitting stdout during the MCP handshake and corrupting it for clients that don’t tolerate non-JSON lines. I watched my own client’s stdout channel for exactly this the entire session — it never happened. The line is there (I saw it in the process’s stderr), but on Compose Hot Reload 1.2.0 it’s written to stderr, not stdout, so it never touched the protocol channel. Worth checking your own version if a handshake fails mysteriously, but I can’t reproduce the corrupted version from a clean 1.12.0 project.</p><p>One more honest note on plumbing: I wasn’t running as the Claude Code CLI sitting inside this project’s directory, so .mcp.json couldn’t be picked up automatically the way it would be for you. I spoke MCP directly over stdio with a small Python client instead — same protocol, same JSON-RPC calls, same tool results, just driven by a script rather than built-in tooling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b3a0ce127ac4e14826588bc440f36ef/href">https://medium.com/media/2b3a0ce127ac4e14826588bc440f36ef/href</a></iframe><p>MCP stdio client: does the initialize handshake, lists tools, and relays tools/call requests dropped into a file queue, decoding any returned image content to PNG.)</p><p>If you’re running this from an actual MCP-aware agent with .mcp.json in the project root, you can skip this part entirely — it&#39;s already wired for you.</p><h3>The Bug I Didn’t Tell It About</h3><p>With the app connected, I added a second screen: a tiny task list. A text field, an <strong>Add</strong> button, a column that lists whatever’s been typed in. I planted one bug and didn’t write down what it was anywhere the agent could read.</p><p>First move: get_semantic_tree to find real node IDs instead of guessing pixel coordinates.</p><pre>{&quot;id&quot;:23,&quot;testTag&quot;:&quot;task_input&quot;, ...}<br>{&quot;id&quot;:31,&quot;role&quot;:&quot;Button&quot;,&quot;text&quot;:&quot;Add&quot;,&quot;testTag&quot;:&quot;task_add_button&quot;, ...}<br>{&quot;id&quot;:34,&quot;testTag&quot;:&quot;task_list_container&quot;, &quot;bounds&quot;:{&quot;width&quot;:0,&quot;height&quot;:0}}</pre><p>Empty container, zero-size bounds — expected, nothing’s been typed yet. So: type_text &quot;Buy milk&quot; into node 23, click node 31. Type &quot;Walk the dog&quot;, click Add again. Then get_semantic_tree one more time to see what actually landed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*GCa4bZRUPjDl457rQDSTdw.png" /><figcaption>Demo UI 1.0</figcaption></figure><p>The text field shows “Walk the dog” — the most recent thing typed. The list below shows exactly one item: “Buy milk.” Not zero items, not two. One. And it’s the <em>older</em> one. That’s a very specific, very telling shape of failure — the UI isn’t frozen, it’s exactly one interaction behind wherever the last unrelated state change left it.</p><p>That shape points at one cause: something in the screen <em>is</em> wired to Compose’s observation system (the text field updates instantly, every keystroke), and something else <em>isn’t</em>. Reading the source confirmed it — the task list lived in a plain mutableListOf&lt;String&gt;(), not mutableStateListOf&lt;String&gt;():</p><pre>val tasks = remember { mutableListOf&lt;String&gt;() }</pre><p>Mutating a plain list doesn’t tell Compose anything happened, so nothing that reads tasks recomposes because of it. The only reason the list ever appeared to update at all was that typing into the field <em>did</em> trigger a recomposition (because newTask is real Compose state), and that recomposition happened to re-read whatever was in tasks at that exact moment — always one click stale.</p><h3>The Fix</h3><p>File before fix: <em>TaskListScreen.buggy.kt</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6610203ea0fa1c5763892704e5d49ace/href">https://medium.com/media/6610203ea0fa1c5763892704e5d49ace/href</a></iframe><p>Code after fix: <em>TaskListScreen.fixed.kt</em></p><pre>val tasks = remember { mutableStateListOf&lt;String&gt;() }</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ccec00b0302034c80575e17548d165a/href">https://medium.com/media/3ccec00b0302034c80575e17548d165a/href</a></iframe><p>mutableStateListOf returns a SnapshotStateList — a list Compose actually watches. Save, reload:</p><pre>{&quot;success&quot;: true, &quot;reloaded&quot;: true}</pre><p>18 seconds, no restart, no lost window position. Then the actual test: type “Buy milk,” click Add <em>once</em>, and check the semantic tree without touching anything else first — no incidental recomposition from a second keystroke to hide behind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*hY8CqvwnYgzHU4jt7yPWKA.png" /><figcaption>Demo UI 1.2</figcaption></figure><p>Both tasks, present after their own click, nothing borrowed from a later one. status confirmed it from the runtime side too: successfulReloads: 1, failedReloads: 0.</p><h3>Where This Falls Apart</h3><p>It’s marked experimental, and it earns that label in a few specific ways worth knowing before you plan a workflow around it:</p><ul><li><strong>It’s desktop-only.</strong> This is JVM-target Compose Hot Reload. It has nothing to do with debugging a Compose app on an Android device or emulator — don’t reach for this expecting mobile inspection.</li><li><strong>take_screenshot isn&#39;t a true headless render.</strong> In my setup, a screenshot taken while the app window wasn&#39;t actually visible on-screen returned whatever <em>was</em> on screen — once literally my desktop wallpaper, not an error. The tool description promises Compose-content-only, decoration-excluded capture, and once the window was frontmost that&#39;s exactly what I got. But &quot;frontmost&quot; turned out to be doing real work there, which isn&#39;t obvious from the tool description alone.</li><li><strong>Task names aren’t as generic as the </strong><strong>.mcp.json example implies.</strong> The unqualified hotMcpServer in the config resolved fine for me — Gradle matched it to the one real task, hotMcpServerDesktop — but the <em>run</em> task has no such forgiving default. Know your target name.</li><li><strong>State doesn’t survive a reload if the </strong><strong>remembered type changes.</strong> Switching mutableListOf to mutableStateListOf reset the list to empty on reload, which is correct behavior, not a bug — but it&#39;s worth expecting if your fix changes a value&#39;s shape, not just its logic.</li></ul><p>None of these are fatal. All of them are the kind of thing you only learn by actually running it, which is presumably why the label says experimental and not beta.</p><h3>What This Signals</h3><p>The interesting part isn’t that an agent found a mutableListOf bug — that&#39;s a Compose 101 mistake, and plenty of linters could flag it statically without any of this machinery. The interesting part is <em>how</em> it found it: not by reading the line and recognizing a pattern, but by clicking a real button, typing real text, and noticing that what came back didn&#39;t match what should have come back. That&#39;s closer to how you&#39;d actually debug it yourself.</p><p>The edit → run → verify loop has always been the developer’s job to close by hand. Giving the agent a standing connection into the running app — not a pasted screenshot, not a described symptom, an actual take_screenshot and get_semantic_tree call it can make on its own — moves the &quot;verify&quot; step from something you do <em>to</em> the agent&#39;s output to something the agent does <em>before</em> it hands the output back to you. It&#39;s one Gradle task, marked experimental, desktop-only for now. But it&#39;s a real instance of the thing everyone&#39;s been gesturing at when they talk about agents needing &quot;grounding&quot; — and for once, you can ./gradlew your way into checking that claim yourself.</p><p>If this helped, follow me here for more real, hands-on looks at what’s actually shipping in Compose — no rewritten release notes, just what happened when I ran it. 👏</p><p><strong>Github Repo</strong></p><p><a href="https://github.com/Majid460/ComposeHotReloadDemo">GitHub - Majid460/ComposeHotReloadDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d4546417f8" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/i-gave-my-ai-agent-eyes-inside-a-real-compose-app-e7d4546417f8">I Gave My AI Agent Eyes Inside a Real Compose App</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recomposition: The Silent Performance Killer in Your Jetpack Compose App]]></title>
            <link>https://proandroiddev.com/recomposition-the-silent-performance-killer-in-your-jetpack-compose-app-3b044fc88c21?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b044fc88c21</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[compose-performance]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 14:53:13 GMT</pubDate>
            <atom:updated>2026-08-27T14:53:13.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kd884C-YkD_bPBzzMaesDA.png" /><figcaption><strong>Cover artwork created by the author</strong></figcaption></figure><p>You didn’t write a bug. You wrote a Composable that runs 47 times a second. Here&#39;s how to catch it before your users do.</p><p>Picture this. You just shipped a beautiful screen built entirely in Jetpack Compose. It looks great in the emulator. QA signs off. Two weeks later, a 1-star review shows up: <em>“App gets laggy when I type in the search bar.”</em></p><p>You didn’t touch the search bar logic. You didn’t add a loop. You didn’t do anything <em>wrong</em>, technically. And that’s exactly the problem — recomposition bugs are invisible in the code and only visible in the <em>runtime</em>. They don’t throw exceptions. They don’t fail your unit tests. They just quietly redraw half your screen every time you blink.</p><p>Let’s fix that.</p><h3>What Recomposition Actually Is (and Why It’s Not “Just Repainting”)</h3><p>Compose’s whole pitch is: describe your UI as a function of state, and let the framework figure out what changed. When state changes, Compose calls your composable function again — this is <strong>recomposition</strong>. In theory, Compose is smart enough to skip composables whose inputs haven’t changed.</p><p>In practice, that “smart skipping” depends entirely on <strong>stability</strong> — a compiler-level guarantee that Compose can trust a value not to have silently changed between reads. Break stability, even accidentally, and Compose stops skipping. It just re-runs everything, every time, defensively.</p><p>That’s the trap: your code looks idiomatic, your app compiles cleanly, and yet you’ve quietly opted every screen using that composable out of skipping.</p><h3>The Classic Culprit: Unstable Parameters</h3><p>Here’s a composable that looks completely normal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d09c2e0e919cf69e1a453a2ae93c943/href">https://medium.com/media/1d09c2e0e919cf69e1a453a2ae93c943/href</a></iframe><p>Nothing screams “danger” here. But List&lt;String&gt; is a <strong>mutable interface</strong> — Compose&#39;s compiler can&#39;t prove it&#39;s immutable, since someone, somewhere, could be holding a MutableList behind that reference. So UserProfile gets marked <strong>unstable</strong>, and every parent recomposition forces ProfileHeader to recompose too, even if profile is functionally identical to last time.</p><p>Multiply that across a list of 50 profiles in a LazyColumn, and you&#39;ve got 50 unnecessary recompositions on every scroll-triggered state change.</p><h3>The Fix: Immutable Collections</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d0ba3cf0b3f87b8a1e9ee2a68d96111/href">https://medium.com/media/4d0ba3cf0b3f87b8a1e9ee2a68d96111/href</a></iframe><p>Swapping List for kotlinx.collections.immutable.ImmutableList gives the Compose compiler a real guarantee, and UserProfile becomes stable again. This single change can eliminate entire classes of recomposition storms in list-heavy screens.</p><h3>The One Tool That Tells You the Truth: Layout Inspector’s Recomposition Counts</h3><p>Don’t guess — measure. Android Studio’s Layout Inspector has a <strong>Recomposition Counts</strong> view that shows you exactly how many times each composable recomposed and skipped during a session.</p><pre>1. Run your app on a device or emulator<br>2. Open View &gt; Tool Windows &gt; Layout Inspector<br>3. Enable &quot;Show Recomposition Counts&quot;<br>4. Interact with your screen<br>5. Look for numbers that seem... suspicious</pre><p>If you see a composable with a recomposition count in the hundreds after typing three characters into a text field, you’ve found your culprit. This is the single fastest way to go from “the app feels laggy” to “line 214 is the problem.”</p><p>This is what a <em>healthy</em> recomposition should actually look like — one state change rippling only through the branches that depend on it, while everything else stays completely still:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLO83kNYfajltg6PaxJN8Q.png" /><figcaption>One state change, selective recomposition — only SearchField and ResultsList re-render (green, solid), while HeaderBar and ProfileAvatar are correctly skipped (dashed, dim) — <strong>Diagram Generated by Author for this article</strong></figcaption></figure><p>That’s the target. Every fix in this post is really just different ways of getting your composable tree to behave like the diagram above instead of lighting up top to bottom on every keystroke.</p><h3>Lambdas: The Sneaky Recomposition Trigger</h3><p>This one bites almost everyone at least once:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb26b4c9ae1e281288ec31a41d51f66f/href">https://medium.com/media/bb26b4c9ae1e281288ec31a41d51f66f/href</a></iframe><p>That trailing lambda is recreated as a <strong>new object</strong> on every recomposition of ProductScreen. If ProductList isn&#39;t using stable, remembered callbacks, Compose can&#39;t confirm the lambda didn&#39;t change — so it can&#39;t skip.</p><h3>The Fix: Remember Your Callbacks</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed7e66004863f3ffce9d93284bcebc5/href">https://medium.com/media/2ed7e66004863f3ffce9d93284bcebc5/href</a></iframe><p>Now the lambda’s identity is stable across recompositions, and Compose can actually do the skipping it was designed to do.</p><h3>derivedStateOf: The Most Underused Tool in the Compose Toolkit</h3><p>Here’s a scenario that trips up even experienced Compose developers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e85b0352df24beade5e2e405d4a9e92/href">https://medium.com/media/8e85b0352df24beade5e2e405d4a9e92/href</a></iframe><p>The fix isn’t caching the filter — it’s telling Compose <em>“this derived value has its own change lifecycle, separate from the state that produced it.”</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5031920f68d1749a9a5e26b17d1474a/href">https://medium.com/media/f5031920f68d1749a9a5e26b17d1474a/href</a></iframe><p>If typing “a” then “ab” then deleting back to “a” produces the <em>same filtered list</em> as before, derivedStateOf recognizes that and skips downstream recomposition entirely. This is the difference between a search bar that feels instant and one that visibly stutters on a mid-range device.</p><h3>Scoping: Don’t Let One State Field Recompose the Whole Screen</h3><p>The final trap is architectural, not syntactic. Watch what happens here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dff6d45b90eeab85da8acff5ff70fe4/href">https://medium.com/media/8dff6d45b90eeab85da8acff5ff70fe4/href</a></iframe><p>If uiState is a single data class with isOtherUserTyping flickering constantly, every read of uiState inside ChatScreen ties the whole composable&#39;s scope to that flicker — even composables that don&#39;t care about typing indicators can get pulled into recomposition depending on how state is read.</p><h3>The Fix: Narrow the Read, Narrow the Recomposition</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b9f3917d9de390d4c506a22d0475d5/href">https://medium.com/media/61b9f3917d9de390d4c506a22d0475d5/href</a></iframe><p>By splitting one broad StateFlow&lt;UiState&gt; into narrower flows read at the point of use, each composable only recomposes for the state it actually depends on. Header no longer cares that someone is typing.</p><h3>The Mental Model Worth Keeping</h3><p>Every time you write a composable, ask yourself one question: <em>“If I called this function again with the exact same-looking data, would Compose be able to tell nothing changed?”</em></p><p>If the answer is “no, because it’s a List, a lambda, or a bundled state object,&quot; you&#39;ve just found your next performance bug before your users do.</p><p>Compose gives you an enormous amount of power for free — but “free” recomposition-skipping only works when you hand the compiler guarantees it can actually verify. Stability isn’t a nice-to-have optimization; it’s the entire mechanism the framework relies on to stay fast.</p><p><em>If this saved you a debugging session, give it a clap 👏 — and if you’ve hit a recomposition bug weirder than these, drop it in the comments. I collect them.</em></p><p><a href="https://medium.com/u/e1f26db83092">Android Developers</a> <a href="https://medium.com/u/eac743c05401">ProAndroidDev.com</a> <a href="https://medium.com/u/2831003aeea2">Android development with Kotlin</a> <a href="https://medium.com/u/6365ee0a4264">Jetpack Compose Dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b044fc88c21" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/recomposition-the-silent-performance-killer-in-your-jetpack-compose-app-3b044fc88c21">Recomposition: The Silent Performance Killer in Your Jetpack Compose App</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Burning Tokens: How I Built a Caching + Offline Fallback Layer for Android LLM Apps]]></title>
            <link>https://medium.com/@majidshahbaz75/stop-burning-tokens-how-i-built-a-caching-offline-fallback-layer-for-android-llm-apps-f98a5ef641b0?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/f98a5ef641b0</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-on-device-ai]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 12:24:59 GMT</pubDate>
            <atom:updated>2026-06-22T13:51:13.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*UmTNYZCW7Vtqi_aO.png" /></figure><p>A drop-in library that cuts your AI API bill, survives dead Wi-Fi, and still answers when the network doesn’t</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k_mxM_QaO9ppBgqH8qKZQ.png" /></figure><p><em>Choose your model on first launch · full control over models and resources · smart Markdown rendering — all from the included demo app.</em></p><p>If you’ve shipped an Android app that talks to an LLM, you already know the three problems that show up the moment real users get their hands on it.</p><p>Someone asks the same question twice. You pay for it twice.</p><p>The subway tunnel kills the connection. Your “AI-powered” screen becomes a spinner of shame.</p><p>And the model that runs beautifully on a flagship chokes the budget phone you forgot existed.</p><p><strong>Memo</strong> is a small Kotlin library built to make all three of these someone else’s problem — yours, specifically, solved, in about four lines of code.</p><h3>The Idea Is Simple: Don’t Ask Twice</h3><p>Every LLM call your app makes is a prompt going out and tokens coming back — and tokens cost money, every single time, even when the answer hasn’t changed since the last person asked.</p><p>Memo sits between your app and whatever model you’re calling. It hashes the prompt, checks a local, TTL-based cache, and if it’s seen that exact question before, it returns the answer instantly — no network round-trip, no tokens billed, no latency. If it’s new, it calls your real API like normal and quietly stores the result for next time.</p><p>You don’t restructure your networking layer. You don’t manage a Room database by hand. You call one function:</p><pre>val memo = Memo.Builder(context)<br>    .autoDownloadModel(true)<br>    .build()</pre><pre>lifecycleScope.launch {<br>    memo.resolve(<br>        prompt = &quot;Summarize this article...&quot;,<br>        model = &quot;your-model-name&quot;,<br>        cloudApiCall = { prompt -&gt; yourApiClient.chat(prompt) }<br>    ).collect { token -&gt;<br>        // Tokens stream in from cache, cloud, or on-device.<br>        // Your UI doesn&#39;t need to know which.<br>    }<br>}</pre><p>That’s the entire integration. Memo decides whether to serve from cache, hit the network, or fall back to a model running on the device — and tells you afterward exactly which one it picked.</p><h3>What Happens When the Network Just… Isn’t There</h3><p>This is the part that makes Memo more than a cache. Most apps treat “offline” as a dead end. Memo treats it as a fallback path.</p><p>If there’s no cache hit and no connection, and the user has downloaded an offline model, Memo runs a real quantized LLM directly on the device — Google’s Gemma, via LiteRT-LM. Not a canned response. Not “you’re offline, try again later.” An actual model, actually answering, with zero internet required.</p><p>If there’s no offline model either, Memo degrades gracefully instead of crashing or freezing your UI — your app gets a clear signal it can act on, not a silent failure.</p><p>Every single response carries a source field — CACHE, NETWORK, or OFFLINE_FALLBACK — so your analytics and your UI always know exactly what happened, automatically.</p><h3>Not Every Phone Should Run the Same Model</h3><p>Shipping one model size to every device is the easy choice and the wrong one. A flagship with 12GB of RAM and a three-year-old budget phone are not the same machine, and pretending otherwise means one of them is always having a bad time.</p><p>Memo’s HardwareProfiler checks the device&#39;s RAM and available storage and can route to a <strong>Lite</strong> or <strong>Standard</strong> model tier accordingly — either picked by the user, or resolved automatically against a backend you control:</p><pre>val memo = Memo.Builder(context)<br>    .modelResolverEndpoint(&quot;https://your-backend.vercel.app/api/resolve-model&quot;)<br>    .autoDownloadModel(true)<br>    .build()</pre><p>Don’t want to stand up a backend? You don’t need one. Point Memo at a static download URL, or skip tiering entirely. A full reference backend (Vercel + Cloudflare R2) ships alongside the project for anyone who wants the complete picture, but it’s optional — Memo works without it.</p><h3>Built Like a Library, Not a Demo</h3><p>The part that should give you confidence using this in a real app: <strong>memo-core</strong>, the module doing the actual hashing, TTL logic, and cost estimation, has zero Android dependencies. It&#39;s pure Kotlin, fully unit tested, and Kotlin Multiplatform–ready. The Android-specific pieces — Room persistence, ConnectivityManager network observation, LiteRT inference — live in a separate memo-android module that wires that core logic into the real platform.</p><p>That separation matters. It means the hard logic isn’t tangled up with Android plumbing, and it’s why the included demo app isn’t a toy — it’s a complete, production-quality Jetpack Compose reference app with real-time streaming chat, a live animated network indicator, full Markdown rendering, hardware-aware model selection, and a proper download lifecycle with progress and cancellation. It’s the same app the screenshots in the README come from.</p><h3>Provider-Agnostic by Design</h3><p>Memo doesn’t care who you call. cloudApiCall accepts any suspend function that takes a prompt and returns text — OpenAI, Gemini, Claude, Groq, your own fine-tuned endpoint, whatever you&#39;ve already built. Memo isn&#39;t asking you to switch providers. It&#39;s asking your existing provider to stop getting billed for questions it&#39;s already answered.</p><h3>Getting Started</h3><p>Add JitPack to your repositories:</p><pre>dependencyResolutionManagement {<br>    repositories {<br>        maven(&quot;https://jitpack.io&quot;)<br>    }<br>}</pre><p>Add the dependency:</p><pre>dependencies {<br>    implementation(&quot;com.github.Majid460.memo-cache-android:memo-android:1.0.0&quot;)<br>}</pre><p>Requirements: minSdk 24+, Kotlin 1.9+, AndroidX. That’s it — no rewrite, no new architecture to learn.</p><h3>Where It’s Headed</h3><p>Memo already covers the core problem end to end: hashing and TTL caching, Room persistence, cost tracking, on-device fallback, hardware-aware tiering, live network observability, and a full demo app to prove it all out. Next on the roadmap: background downloads via WorkManager, Kotlin Multiplatform support, and persisted chat history.</p><p>It’s MIT licensed, it’s open source, and it’s built by one developer who got tired of watching avoidable API calls fly out the door.</p><p>If you’re building anything on Android that talks to an LLM, give it a look:</p><p><a href="https://github.com/Majid460/memo-cache-android"><strong>github.com/Majid460/memo-cache-android</strong></a></p><p>A star on the repo costs nothing and helps more than you’d think. If you try it and hit a rough edge, open an issue — that’s how this gets better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98a5ef641b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Refactored a “Working” Jetpack Compose App Into a Production-Ready Architecture and It Changed…]]></title>
            <link>https://medium.com/@majidshahbaz75/i-refactored-a-working-jetpack-compose-app-into-a-production-ready-architecture-and-it-changed-5d78d4c6e949?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d78d4c6e949</guid>
            <category><![CDATA[nav-3]]></category>
            <category><![CDATA[android-cleanarchitecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[sqldelight]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 18:04:22 GMT</pubDate>
            <atom:updated>2026-03-09T18:04:22.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Refactored a “Working” Jetpack Compose App Into a Production-Ready Architecture and It Changed Everything</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gZLcxt6j5FDPmHjjvjOTQ.png" /><figcaption>&lt;NewsApp&gt;</figcaption></figure><p>Most Android apps don’t fail because the UI is ugly.<br>They fail slowly, over time, when adding one new feature breaks three old ones.</p><p>That was exactly the situation here.</p><p>The app looked fine. It fetched news. It had favorites. It had some architectural pieces already in place. But under the surface, responsibilities were mixed, auth behavior was inconsistent, and local persistence wasn’t aligned with a scalable feature model.</p><p>So I decided to treat it like a real production codebase and refactor it as if a team would maintain it for years.</p><p>This is the story of that refactor.</p><h3>Chapter 1: The app worked… until you looked closer</h3><p>At first glance:</p><ul><li>Home showed news</li><li>Favorites existed</li><li>There were ViewModels</li><li>There were use cases</li><li>There was dependency injection</li></ul><p>So what was wrong?</p><p>A lot of “almost clean” architecture:</p><ul><li>partial MVI, not consistently enforced</li><li>favorites tied to older persistence path</li><li>no real user-scoped local auth model</li><li>navigation auth behavior felt abrupt</li><li>placeholders in key screens (article detail/profile)</li><li>structure that looked clean from afar but leaked concerns between layers</li></ul><p>This is the dangerous zone: code that compiles and demos well, but becomes expensive with every new requirement.</p><h3>Chapter 2: New goal: build for maintenance, not demo</h3><p>The direction was clear:</p><ul><li>Feature-first architecture</li><li>MVI per feature</li><li>Clean boundaries between UI, domain, and data</li><li>SQLDelight for local relational persistence</li><li>Hilt for wiring</li><li>Flow/StateFlow for reactive updates</li><li>Better UX and consistent behavior</li></ul><p>And importantly: <strong>don’t rewrite blindly</strong>.<br>Refactor incrementally, keep it runnable.</p><h3>Chapter 3: The architecture shift</h3><p>I reorganized around feature ownership:</p><ul><li>feature/home</li><li>feature/auth</li><li>feature/favorites</li><li>feature/profile</li></ul><p>Each feature follows MVI contracts:</p><ul><li>State</li><li>Action</li><li>Event</li><li>Reducer</li><li>ViewModel</li></ul><p>This instantly clarified responsibilities:</p><ul><li>UI only renders state and dispatches actions</li><li>reducers own state transitions</li><li>use cases own business decisions</li><li>repositories own data access</li></ul><p>No more “UI deciding business logic on the fly.”</p><h3>Chapter 4: SQLDelight became the real backbone</h3><p>The most important structural move was local data.</p><p>I moved local persistence to SQLDelight with two core tables:</p><ul><li>User(id, email, passwordHash)</li><li>Favorites(id, articleId, userId, …)</li></ul><p>Then added session storage in DataStore (currentUserId) to connect auth state to favorites state.</p><p>This unlocked proper behavior:</p><ul><li>favorites are now truly <strong>per user</strong></li><li>login and register are explicit flows</li><li>profile can reliably show user + favorites count</li></ul><p>And because SQLDelight generates typed query APIs, accidental query/model mismatches are drastically reduced.</p><h3>Chapter 5: Auth finally felt like auth</h3><p>Before: login behavior was too loose.<br>Now:</p><ul><li>register creates account only if user doesn’t exist</li><li>login succeeds only for existing user + matching password hash</li><li>both update local session</li><li>profile and favorites react from session state</li></ul><p>It’s simple local auth, but structurally correct.</p><h3>Chapter 6: UX fixes that matter in real usage</h3><p>A few UX changes had outsized impact:</p><h3>Favorites access behavior</h3><p>Instead of hard redirecting when logged out, favorites now shows an inline prompt:<br>“Login required” + button to login.</p><p>That sounds small, but it feels much less jarring.</p><h3>Article detail screen</h3><p>Implemented a real in-app reader (WebView) with loading state and fallback for invalid URLs.</p><h3>Top app bar behavior</h3><p>Back button now appears consistently for non-top-level routes, including article detail.</p><h3>Profile redesign</h3><p>Profile screen was transformed into an elevated, modern card with:</p><ul><li>user status chip</li><li>email section</li><li>favorites metric</li><li>polished action buttons</li><li>gradient-backed visual hierarchy</li></ul><h3>Global visual consistency</h3><p>Applied shared gradient shell styling so screens feel part of one product, not separate demos.</p><h3>Chapter 7: Docs and trust signals</h3><p>Good architecture without good documentation still slows teams down.</p><p>So I updated README with:</p><ul><li>clear feature/behavior explanation</li><li>full code structure</li><li>architecture diagram</li><li>screenshots section</li><li>build/test commands</li><li>external badges for tech visibility</li></ul><p>I also created a social preview image so repository sharing looks professional.</p><h3>Chapter 8: Testing the right places</h3><p>Instead of adding random tests, I targeted the highest-leverage points:</p><ul><li>Auth reducer transitions</li><li>Home reducer transitions</li><li>Favorites use-case behavior</li></ul><p>MVI reducers are deterministic and perfect for unit tests.<br>These tests act like guardrails during future refactors.</p><h3>The biggest lesson</h3><p>The hardest part of Android architecture is not picking libraries.<br>It’s enforcing boundaries consistently when requirements evolve.</p><p>Once boundaries are clear:</p><ul><li>adding register flow is easy</li><li>changing favorites auth logic is easy</li><li>redesigning profile UI doesn’t leak into data code</li><li>debugging state becomes predictable</li></ul><p>That’s what “production-ready” really means.</p><h3>Final state in one line</h3><p>A demo-like news app became a maintainable product foundation using:</p><p><strong>Compose + MVI + Clean Architecture + Hilt + SQLDelight + Flow</strong></p><p>And that combination, when done with discipline, scales surprisingly well.</p><p><strong>Repository:</strong></p><p><a href="https://github.com/Majid460/Jetpack-NewsApp">GitHub - Majid460/Jetpack-NewsApp: Production-ready Android News app with Jetpack Compose, MVI, Clean Architecture, Hilt, SQLDelight, Flow.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d78d4c6e949" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beating Type Erasure: How Kotlin’s inline + reified Unlock Compile-Time Superpowers]]></title>
            <link>https://medium.com/@majidshahbaz75/beating-type-erasure-how-kotlins-inline-reified-unlock-compile-time-superpowers-e7b6258a677c?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b6258a677c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[reified]]></category>
            <category><![CDATA[kotlin-reified]]></category>
            <category><![CDATA[inline]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 11:34:14 GMT</pubDate>
            <atom:updated>2026-02-19T11:34:14.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Kp-D1-UUIFX4w_MJxc1NQ.png" /><figcaption>&lt;Reified.1000001&gt;&lt;Inline.1000002&gt;</figcaption></figure><h3><strong>Introduction</strong></h3><p>Kotlin is packed with powerful features that help developers write expressive and efficient code, but few are as misunderstood (or underused) as the inline keyword and its companion, reified. At first glance, they might seem like advanced compiler tricks reserved for library authors.</p><p>In reality, they solve everyday problems: eliminating lambda overhead, enabling type-safe generic functions, and making your code both cleaner and more performant. In this article, we&#39;ll break down exactly what inline and reified do, why they exist, and when you should reach for them.</p><h3>What Is the inline Keyword?</h3><p>The inline keyword is used to optimize higher-order functions by reducing the runtime overhead associated with function calls, particularly when lambda expressions are involved.</p><p>When a function is marked as inline, the Kotlin compiler substitutes the function body directly into the places where the function is called. This substitution eliminates the need to allocate memory for function objects and avoids the overhead of lambda invocation.</p><h3>How Inlining Works Under the Hood</h3><p>Normally, passing a lambda as a parameter involves creating an object to represent the lambda and invoking its method. This can introduce performance overhead, especially in performance-critical scenarios. Marking a function as inline eliminates this overhead by inserting the actual function body and lambda code directly into the call site. Consider the following example:</p><pre>private inline fun inlineFun(lambda: () -&gt; Unit) {<br>    println(&quot;COMPUTING started&quot;)<br>    lambda() // The code from the lambda will be copied here<br>    println(&quot;Computing ended&quot;)<br>}<br><br>fun main() {<br>    inlineFun { println(&quot;Performing heavy computing&quot;) }<br>}</pre><p>In this example, the inlineFun function is marked as inline. The compiler will replace the call to inlineFun with its body, including the lambda code, resulting in fewer object allocations and better runtime performance.</p><h3>Performance Benefits: Lambda Overhead Explained</h3><p>Without using inline, every time you pass a lambda to a higher-order function, the compiler must create a function object on the heap to represent that lambda. This includes:</p><p><strong>1. Object Allocation: </strong>A new object is created on the heap to hold the lambda’s code.</p><p><strong>2. Memory Overhead:</strong> This object consumes memory.</p><p><strong>3. Virtual Method Call:</strong> Invoking the lambda requires a virtual method call (invoke()), which slightly slower than a direct method call.</p><p>In a function that is called frequently, especially within a loop, this overhead of creating many small Function objects can add up and impact performance by putting pressure on the garbage collector.</p><p>The inline keyword solves this completely. When a function is inlined, the compiler doesn’t create a Function object for the lambda. Instead, it pastes the body of the lambda directly where it is called.</p><pre>// Inline Function<br>private inline fun inlineFun(lambda: () -&gt; Unit) {<br>    println(&quot;COMPUTING started&quot;)<br>    lambda() // The code from the lambda will be copied here<br>    println(&quot;Computing ended&quot;)<br>}<br><br>// Non Inline Function<br>private fun nonInlined(lambda: () -&gt; Unit) {<br>    println(&quot;COMPUTING started&quot;)<br>    lambda() // This is a virtual call to a Function object<br>    println(&quot;Computing ended&quot;)<br>}<br><br>fun main() {<br>    inlineFun { println(&quot;Performing heavy computing&quot;) }<br>    nonInlined { println(&quot;Performing heavy computing&quot;) }<br>}<br><br>// What the compiler generates<br><br>fun main_compiled() {<br>    // For nonInlined, a Function object is created<br>    println(&quot;COMPUTING started&quot;)<br>    Function0 { println(&quot;Performing heavy computing&quot;) }.invoke()<br>    println(&quot;Computing ended&quot;)<br><br>    // For inline Function, the code is copied directly<br>    println(&quot;COMPUTING started&quot;)<br>    println(&quot;Performing heavy computing&quot;) // No object, no virtual call<br>    println(&quot;Computing ended&quot;)<br>}</pre><h3>Introducing reified: Retaining Type Information at Runtime</h3><p>Another powerful feature unlocked by inline is the ability to use reified type parameters. In Kotlin, generics are erased at runtime due to type erasure in the JVM, which means you cannot access the type of a generic parameter T at runtime (e.g., you can&#39;t do T::class).</p><p>However, by marking a function as inline, you can use the reified keyword to retain type information at runtime. This is particularly useful for type-checking or casting.</p><pre>private inline fun &lt;reified T&gt; isInstance(value: Any): Boolean {<br>    return value is T<br>}<br><br>fun main() {<br>    println(isInstance&lt;String&gt;(&quot;This is string&quot;)) // true<br>    println(isInstance&lt;Int&gt;(&quot;This is Int&quot;))       // false<br>}</pre><p>In this example, reified allows the type parameter T to be used in a type-checking operation (is T) at runtime. This is extremely useful for creating clean, type-safe APIs, especially in libraries. A common use case in Android is finding a Fragment by its type: findFragment&lt;MyFragment&gt;().</p><h3>Benefits of Using reified</h3><p>When working with generics in Kotlin, using the reified keyword in inline functions unlocks powerful capabilities that are otherwise restricted due to type erasure. Here are the key advantages:</p><ol><li><strong>Type Safety:</strong> Allows for safer code by reducing the need for unchecked casts.</li><li><strong>Cleaner Syntax:</strong> Removes the requirement for explicitly passing Class objects as parameters.</li><li><strong>Runtime Reflection:</strong> Enables easier runtime operations like checking types or accessing class metadata.</li></ol><pre>inline fun &lt;reified T&gt; List&lt;Any&gt;.filterByType(): List&lt;T&gt; {<br>    return this.filterIsInstance&lt;T&gt;()<br>}<br><br>fun main() {<br>    val mixedList = listOf(1, &quot;Class A&quot;, 2.5, &quot;Programming&quot;)<br>    val stringList = mixedList.filterByType&lt;String&gt;()<br>    println(stringList) // Outputs: [Class A, Programming]<br>}</pre><p>Here, the filterByType function retains type information through reified, enabling type-specific filtering.</p><h3>Limitations of reified and Inline</h3><h3>Inline</h3><ol><li><strong>Code bloat</strong> — large functions copied at every call site increase binary size and can cause CPU cache misses.</li><li><strong>Large functions</strong> — substantial logic should stay non-inlined to keep your APK lighter and runtime efficient.</li><li><strong>No overriding</strong> — inline functions are implicitly final, making them unsuitable for polymorphic or inheritance-based designs.</li><li><strong>No lambdas, no benefit</strong> — without lambda parameters, the JVM’s JIT compiler handles inlining better than doing it manually.</li><li><strong>Avoid with recursion</strong> — recursive functions cannot be inlined; the compiler will warn you if you try.</li><li><strong>Limited use as private functions</strong> — private inline functions offer little advantage if they aren&#39;t reused across multiple call sites.</li></ol><h3>Reified</h3><ol><li>Only works inside inline functions — it cannot be used for general-purpose generics outside that context.</li><li>The JVM’s type erasure is why this limitation exists; generic types are lost at runtime by default.</li><li>Must be used judiciously — forces the function to be inline and can cause code bloat if overused.</li><li>Best suited for utility functions or framework code where type introspection and flexibility are genuinely needed.</li></ol><h3>Key Takeaways</h3><h3>Inline</h3><ol><li>Substitutes the function body and lambdas directly at the call site, cutting down memory allocation and runtime overhead.</li><li>Particularly effective when lambdas are used frequently, as it avoids the cost of object creation for each call.</li><li>Unlocks the ability to use reified generics, which is otherwise impossible in regular functions.</li><li>Overusing it can lead to code bloat — the more places a large function is inlined, the larger the compiled output becomes.</li><li>Apply it judiciously: best suited for small, frequently called higher-order functions rather than large or rarely used ones.</li></ol><h3>reified</h3><ol><li>Allows access to generic type information at runtime, which is normally erased by the JVM.</li><li>Makes type-based operations safer, cleaner, and more readable.</li><li>Best suited for runtime reflection or type manipulation scenarios.</li><li>Only works inside inline functions — it cannot be used in regular generic programming.</li></ol><h3>Conclusion</h3><p>The inline keyword and reified generics are among Kotlin&#39;s most powerful yet nuanced features. When applied thoughtfully, they eliminate boilerplate, improve runtime performance, and enable type-safe operations that would otherwise require verbose workarounds. However, like any optimization tool, they come with trade-offs such as code bloat, design constraints, and limited applicability outside specific contexts. The key is knowing when to reach for them and when to step back. As you grow more comfortable with these features, you&#39;ll find they naturally slot into the right places in your codebase, making your Kotlin code not just more efficient, but more expressive and elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b6258a677c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Illusion of Productivity: Psychological Traps Developers Fall Into with AI Tools]]></title>
            <link>https://medium.com/@majidshahbaz75/the-illusion-of-productivity-psychological-traps-developers-fall-into-with-ai-tools-b156aecf45d4?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/b156aecf45d4</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai-vs-humans]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 13:47:33 GMT</pubDate>
            <atom:updated>2026-01-17T13:47:33.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29u3Bm8-ZvKKAQ3rJL543A.png" /><figcaption>&lt;101.TITLE.IMAGE&gt;</figcaption></figure><h4><strong>The Search-First Mindset</strong></h4><p>During the early years of development, we were taught ways to solve problems using critical thinking and knowledge. If it was not possible to find a solution after a few tries, the first thing that popped into our minds was to search on Google. If I speak about myself, I mostly read solutions written on Stack Overflow.</p><p>The best thing about Stack Overflow is that all the solutions are written by humans, and we can improve or appreciate the solutions shared there. Most of these solutions are valid and useful.</p><p>If I compare that mindset with how things are now, I can clearly see the difference between how my brain approached solutions back then and how it does today in the AI era. Before AI, the general pragmatic thinking approach involved solutions being passed directly from person to person. We could clearly see who wrote the solution and who took responsibility for it.</p><p>Nowadays, AI provides solutions that are often more refined and efficient than those from previous years. However, we have lost something important: <strong>originality</strong> and <strong>accountability</strong>. One of my main concerns is that AI is taking solutions created by humans, written by humans, for humans, and acting as a proxy between them. These transformative models do not have ownership or true understanding; they are trained to extract information from different sources across the internet.</p><p>I am not an anti-AI person. In fact, I use AI daily for different tasks.</p><h4><strong>The Illusion of Speed and Accountability</strong></h4><p>We all know that developers are shipping code more quickly and efficiently than ever before. Many companies are adopting AI systems in areas where less sensitive information is involved, such as automating certain HR processes.</p><p>While I agree with the speed and performance AI brings to automation, I often think about scenarios like hiring processes, which involve behavioral evaluation and psychological profiling of candidates. This raises certain questions:</p><ol><li>Can an AI-based system understand human psychology the way another human can?</li><li>Can an AI-based system support people emotionally in the same way a human does?</li></ol><p>As developers, writing code and building systems is not just part of the job. Companies do not only hire employees to produce software quickly; they also build cultures and environments that allow developers to work comfortably and with confidence. To create such environments, people must be managed well and supported with strong mental and emotional awareness.</p><p>One might ask why we don’t use AI to do all these tasks instead of hiring humans. While automation has its place, humans require personal attention and understanding. From my experience, a human can understand another human better and can write solutions that are truly meant for humans.</p><p>How can you give advice on something you have never experienced?</p><p>Speed is important for both companies and developers, but accountability matters too. If a human makes a mistake in a system, that individual is accountable for the consequences. But if an AI system makes a mistake, who is responsible? While there are ways to mitigate this, the lack of clear accountability and control remains a concern.</p><p>Productivity is not just about speed. It is also about the ability to make sound decisions based on real-world situations.</p><h4><strong>Direct AI Effects on the Mind</strong></h4><p>I still remember when I used to think that machine learning models would one day help us in certain aspects of life. In my final year at university, I developed an ML-based system to recommend diet plans to patients. Later, during my master’s degree, I developed a Kubernetes pod migration system using Deep Reinforcement Learning (PPO) to make intelligent decisions during overload situations.</p><p>We are the people helping the world design these AI-based systems, so we understand their side effects better than most.</p><p>During our early years, we had strong confidence in our cognitive abilities to design solutions. I consider myself among those who experienced both the human-thinking era and the cognitive AI era. From my experience, I learned more during the human-thinking era because there was one clear path: learn first, then implement.</p><p>Today, many junior developers and students rely heavily on AI instead of learning through books and documentation. While learning how to use AI tools is important, understanding how things actually work is just as critical.</p><p>Many developers are subconsciously reducing long-term learning. Instead of building deep mental models, they rely on short-term memory supported by AI. This leads to fear — fear that AI has taken over — and causes people to panic instead of focusing on developing skills that help them stand out.</p><p>I strongly believe in discipline and control over the mind. The brain controls the human body, and if you can direct it in the right way, you can achieve meaningful growth. This may not be a universal truth, but it is something I deeply believe in.</p><p>Since the AI era began, many of us have lost confidence in ourselves. Our minds are deeply affected. The moment we encounter a problem, we turn to AI instead of thinking on our own. Gen Z, in particular, avoids boredom — yet psychology tells us that boredom is essential for creativity and critical thinking.</p><p>A recent Sonar survey found that <strong>approximately 42% of committed code was AI-generated</strong>, yet <strong>96% of developers say they don’t fully trust AI-generated code</strong> and <strong>less than half always verify it before committing</strong>.</p><p><a href="https://www.techradar.com/pro/devs-dont-trust-ai-code-but-many-say-they-still-dont-check-it-anyways">https://www.techradar.com/pro/devs-dont-trust-ai-code-but-many-say-they-still-dont-check-it-anyways</a></p><h4>Dopamine-Driven Development</h4><p>Instant results lead to instant rewards — this is what I call dopamine-driven development. Instead of sitting with uncertainty and trying to find better solutions, we rely on AI for immediate answers. When those answers work, they deliver a small dopamine hit.</p><p>Instead of wrestling with a problem, we delegate it. The goal shifts from understanding to simply getting an answer.</p><p>This creates a loop: friction appears, AI removes it instantly, a reward is delivered, and tolerance for struggle decreases. What feels like efficiency is often the avoidance of cognitive effort.</p><p>The danger isn’t laziness — it’s conditioning. Developers become less patient with slow progress, less willing to explore dead ends, and more dependent on external validation that something “works.” Debugging, reading source code, and building mental models start to feel unnecessarily hard, even though these are the activities that build real expertise.</p><p>Dopamine-driven development doesn’t make developers less capable — <br> it makes them less comfortable thinking without immediate reward.</p><h4><strong>Reclaiming Thoughtful Productivity</strong></h4><p>Productivity in the AI era should not be measured only by speed or output. Real productivity still requires understanding, judgment, and responsibility. AI can help us move faster, but it cannot decide what is worth building or why.</p><p>The challenge for developers today is not to reject AI, but to use it consciously. Thinking before prompting, sitting with uncertainty, and allowing ourselves to struggle are not inefficiencies — they are investments in long-term skill and confidence.</p><p>AI did not replace our ability to think. We slowly handed parts of it away. Reclaiming thoughtful productivity means choosing when to delegate and when to engage deeply. In a world optimized for speed, the ability to think clearly remains the most valuable skill we have.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b156aecf45d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP Project Setup]]></title>
            <link>https://medium.com/@majidshahbaz75/kmp-project-setup-114da6cffeae?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/114da6cffeae</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[kmp-project-setup]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 12:58:09 GMT</pubDate>
            <atom:updated>2024-02-29T12:58:09.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*VY55onzfXRyjwX-n7qd3MA.png" /></figure><h4><strong>Kotlin Multi Platform</strong></h4><p>Kotlin Multiplatform is a framework for developing cross-platform applications with Kotlin. It allows you to write shared code that can be reused on multiple platforms, such as iOS, Android, macOS, Windows, and Linux. You can also write platform-specific code to access the native features of each platform.</p><h4>Why KMP?</h4><p>Kotlin Multiplatform (KMP) offers several benefits for developers looking to create cross-platform applications:</p><p><strong>1. Code Sharing and Reusability:</strong></p><ul><li>KMP allows you to share a single codebase across different platforms like Android, iOS, macOS, web, and even server-side development. This reduces overall development and maintenance effort compared to writing separate codebases for each platform.</li><li>By sharing core logic and business logic, you can maintain consistency across platforms and focus platform-specific development efforts on UI and features requiring native access.</li></ul><p><strong>2. Native Performance and Access:</strong></p><ul><li>Unlike some cross-platform frameworks, KMP doesn’t rely on web technologies or abstractions. Instead, it compiles down to native code for each platform, ensuring optimal performance and access to native features like platform-specific libraries and APIs. This allows you to deliver a native experience on each platform.</li></ul><p><strong>3. Improved Developer Experience:</strong></p><ul><li>KMP leverages the familiarity and strengths of the Kotlin language, providing a unified development experience across platforms. Developers can write code in a single language, improving code readability and maintainability compared to juggling multiple languages for different platforms.</li></ul><p><strong>4. Flexibility and Control:</strong></p><ul><li>KMP offers various approaches to code sharing. You can choose to share only the core logic or extend to platform-specific code using expect-actual declarations. This flexibility allows you to tailor the level of code sharing based on your project’s needs.</li></ul><p><strong>5. Growing Community and Ecosystem:</strong></p><ul><li>KMP is an actively developed technology with a growing community and ecosystem of libraries and tools. This ongoing development fosters continuous improvement and provides resources for developers building cross-platform applications with KMP.</li></ul><p><strong>However, it’s important to consider these points before choosing KMP:</strong></p><ul><li><strong>Learning Curve:</strong> While leveraging Kotlin offers a familiar language, understanding KMP’s specific concepts and complexities might require additional learning, especially for developers new to cross-platform development.</li><li><strong>Project Complexity:</strong> KMP might not be the best choice for very simple projects, as the initial setup and potential complexity might outweigh the benefits.</li><li><strong>Platform-Specific Considerations:</strong> While KMP promotes shared code, some aspects of your application will still require platform-specific development to ensure a native user experience.</li></ul><h4>KMP Project Setup</h4><p>Install the Kotlin Multiplatform Mobile plugin in android studio.</p><p>Go to android studio settings then click on plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*pfWNXR_x7P6vnjJYP5aZBg.png" /></figure><p>Now install the Kdoctor. Run the following command in android studio terminal.</p><pre>brew install kdoctor</pre><p>Now we can create a new KMP project.</p><p>There are two ways to create a new KMP project.</p><h4>From Android Studio</h4><p>By clicking File -&gt; New -&gt; New Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*xBZoROWDQObuaPXn9ICQ7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*9WdzityMQ8-ZCs9IKqVhlw.png" /></figure><p>Choose the specific project path.</p><p>Then click Next and after gradle building project is ready to work on.</p><p>KMP differs from other frameworks as it allows sharing of the core logic and business logic across platforms like Android, iOS, and more. You write code once and reuse it with platform-specific extensions for UI and features.</p><p>Run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZUviM01HgIEcTw_-QvGoA.png" /><figcaption>IOS Simulator</figcaption></figure><p>Thanks for Reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=114da6cffeae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Flows With Room Database]]></title>
            <link>https://medium.com/@majidshahbaz75/kotlin-flows-with-room-database-2d8b4b18790a?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8b4b18790a</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[flow-state]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-flows-with-room]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 11:20:24 GMT</pubDate>
            <atom:updated>2024-03-04T12:25:02.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZ2iQwJD7VRRuGrZ8XzlNQ.jpeg" /><figcaption>kotlin flows</figcaption></figure><p>In Kotlin we are using state flows to observe data when some change occurs. As state flows are powerful observers introduced by kotlin to use with kotlin coroutines to perform asynchronous operations. Moreover, a suspending function asynchronously returns a single value, but the critical question is how can we return multiple asynchronously computed values? In Kotlin coroutines, a flow is a type that can be able to emit multiple values sequentially like receiving live updates from a database, as opposed to suspend functions that return just only a single value. This article aims to discuss the main concepts, entities, and async possibilities in Kotlin flow.</p><p>I followed MVVM design pattern.</p><h4>Room Entities:</h4><p>Let&#39;s design the room entity first.</p><pre>@Parcelize<br>@Entity(tableName = &quot;books&quot;)<br>data class BooksResponse(<br>    @PrimaryKey<br>    @SerializedName(&quot;_id&quot;)<br>    var _id:String,<br>    @SerializedName(&quot;id&quot;)<br>    var id:String?=null,<br>    @SerializedName(&quot;title&quot;)<br>    var title:String?=null,<br>    @SerializedName(&quot;author&quot;)<br>    var author:String?=null,<br>    @SerializedName(&quot;about&quot;)<br>    var about:String?=null,<br>    @SerializedName(&quot;url&quot;)<br>    var url:String?=null,<br>): Parcelable</pre><p>Table name is the optional parameter to give the name to a table.</p><h4>Room Dao:</h4><p>Room dao is the interface consist of functions to perform operations on database.</p><pre>@Dao<br>interface Dao {<br><br>    @Insert(onConflict = OnConflictStrategy.IGNORE)<br>    suspend fun insertAll(  books: MutableList&lt;BooksResponse&gt;)<br><br>    @Query(&quot;SELECT * FROM books&quot;)<br>    fun getBooks(): Flow&lt;MutableList&lt;BooksResponse&gt;&gt;<br>    @Query(&quot;DELETE FROM books&quot;)<br>    fun delete()<br>}</pre><h4>Database Class:</h4><p>I have used hilt for dependency injection so i just made a abstract class for database and then i linked that class with hilt module.</p><pre>@Database(<br>    entities = [BooksResponse::class],<br>    version=1,<br>    exportSchema = false<br>)<br>abstract class Database:RoomDatabase() {<br>    abstract fun getDao() : Dao<br>}</pre><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>class DatabaseModule {<br>    @Singleton<br>    @Provides<br>    fun providesDB(@ApplicationContext context: Context):Database{<br>        return Room.databaseBuilder(context,Database::class.java,&quot;Database&quot;).build()<br>    }<br>}</pre><h4>Repository:</h4><p>In Repo’s constructor i just passed all the required params using hilt dependency injection.</p><pre>class Repository @Inject constructor(<br>    private val api: ApiInterfaces,<br>    private val externalScope: CoroutineScope,<br>    private val localData: Database,<br>) : BaseRemoteRepo() {<br><br>   fun getBooksLocally(): Flow&lt;NetworkResult&lt;MutableList&lt;BooksResponse&gt;&gt;&gt; {<br>        return localData.getDao().getBooks()<br>            .map { data -&gt;<br>                NetworkResult.success(data)<br>            }<br>            .onStart {<br>                emit(NetworkResult.loading())<br>            }<br>            .catch { exception -&gt;<br>                emit(NetworkResult.error(exception.message ?: &quot;Error Occur&quot;))<br>            }<br>    }<br><br>    suspend fun getBooksData() {<br>        externalScope.launch(Dispatchers.IO) {<br>            safeApiCall {<br>                api.getBooks()<br>            }.also {<br>                it.data?.let { it1 -&gt;<br>                    localData.getDao().insertAll(it1)<br>                }<br>            }<br>        }.join()<br>    }<br><br>     fun deleteData() {<br>        localData.getDao().delete()<br>    }<br><br>    fun destroyScope(){<br>        externalScope.cancel()<br>    }<br>}</pre><p>In Repo i called the api to fetch books from remote and then saved them in local room database and emits the value using flow so when data will load in flow then it will just emit that data to ui.</p><pre>abstract class BaseRemoteRepo {<br><br>    suspend fun &lt;T&gt; safeApiCall(apiCall: suspend () -&gt; Response&lt;T&gt;?): NetworkResult&lt;T&gt; {<br>        try {<br>            val response = apiCall.invoke()<br>            if (response != null &amp;&amp; response.isSuccessful) {<br>                return NetworkResult.success(response.body())<br>            }<br>            val errorBody = response?.errorBody()?.string()<br>            return if (response?.code() == 404) {<br>                NetworkResult.error(&quot;Bad Request&quot;)<br>            } else if (!errorBody.isNullOrEmpty()) {<br>                NetworkResult.error(errorBody)<br>            } else {<br>                NetworkResult.error(&quot;Error in fetching data&quot;)<br>            }<br><br>        } catch (e: Exception) {<br>            println(e.message)<br>            throw RuntimeException(e)<br>        }<br>    }<br>}</pre><h4>ViewModel:</h4><p>In view model i defined the functions that observed all the data changes in the flows and notified the ui.</p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(private val repo: Repository) : BaseViewModel() {<br>    <br>    val booksStateFlow = repo.getBooksLocally()<br><br>    fun deleteBooks() = viewModelScope.launch(Dispatchers.IO) {<br>        repo.deleteData()<br>    }<br>    fun getBooks() = viewModelScope.launch(Dispatchers.IO) {<br>        repo.getBooksData()<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        repo.destroyScope()<br>    }<br>}</pre><h4>Activity:</h4><p>On the activity i just observed the data changes and notify to the adapter.</p><pre>@AndroidEntryPoint<br>class MainActivity: BaseActivity() {<br>    private lateinit var  mainViewModel: MainViewModel<br>    private lateinit var binding: ActivityMainBinding<br>    private lateinit var adapter:BooksAdapter<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        mainViewModel= ViewModelProvider(this)[MainViewModel::class.java]<br>        binding = DataBindingUtil.setContentView(this,R.layout.activity_main)<br><br>        mainViewModel.getAllAuthors()<br><br>        binding.apply {<br>            btnDelete.setOnClickListener {<br>                mainViewModel.deleteBooks()<br>            }<br>            btnFetch.setOnClickListener {<br>                mainViewModel.getBooks()<br>            }<br>        }<br>        setUpAdapter()<br>        lifecycleScope.launch(Dispatchers.Main) {<br>            repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                mainViewModel.booksStateFlow.collect {<br>                    when (it.status) {<br>                        Status.LOADING -&gt;{<br>                            binding.PBar.show()<br>                        }<br>                        Status.SUCCESS -&gt; {<br>                             binding.PBar.hide()<br>                             if(it.data?.isEmpty() == true){<br>                                 binding.tvNoData.show()<br>                             }else {binding.tvNoData.hide()}<br>                             adapter.setItems(it.data?: arrayListOf())<br>                        }<br>                        Status.ERROR -&gt; {<br>                            binding.PBar.hide()<br>                            println(&quot;Shared Flow Error:: &quot;+it.message)}<br>                    }<br>                }<br>            }<br>        }<br>    }<br>  private fun setUpAdapter(){<br>      adapter = BooksAdapter(this){}<br>      binding.apply {<br>          rvBooks.layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.VERTICAL, false)<br>          rvBooks.adapter = adapter<br>      }<br>  }<br>}</pre><p>Generic class for Data Handling:</p><pre>data class NetworkResult&lt;out T&gt;(val status: Status, val data: T?, val message: String?) {<br><br>    companion object {<br><br><br>        fun &lt;T&gt; success(data: T?): NetworkResult&lt;T&gt; {<br>            return NetworkResult(Status.SUCCESS, data, null)<br>        }<br><br><br>        fun &lt;T&gt; error(msg: String): NetworkResult&lt;T&gt; {<br>            return NetworkResult(Status.ERROR, null, msg)<br>        }<br><br><br>        fun &lt;T&gt; loading(): NetworkResult&lt;T&gt; {<br>            return NetworkResult(Status.LOADING, null, null)<br>        }<br>    }<br>}<br><br>// An enum to store the<br>// current state of api call<br>enum class Status {<br>    SUCCESS,<br>    ERROR,<br>    LOADING<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*4-lPHDlD20u58fn6NfdoMg.png" /><figcaption>Books Data</figcaption></figure><p>So just after implemented all the code we have result.</p><p>For more details just check it on github</p><p><a href="https://github.com/Majid460/StateFlows_Kotlin_Architecture">GitHub - Majid460/StateFlows_Kotlin_Architecture: This repository contains the kotlin state flows and mutable state flows and also describes the data flowing with state flows</a></p><p>Thanks for reading.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8b4b18790a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Flows in Android Kotlin]]></title>
            <link>https://medium.com/@majidshahbaz75/state-flows-in-android-kotlin-59267a6f2f98?source=rss-394ad2b31423------2</link>
            <guid isPermaLink="false">https://medium.com/p/59267a6f2f98</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[livedata-vs-stateflows]]></category>
            <category><![CDATA[kotlinandroid]]></category>
            <category><![CDATA[flow-state]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <dc:creator><![CDATA[Majidshahbaz]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 15:39:10 GMT</pubDate>
            <atom:updated>2023-10-10T15:39:10.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*K1cXMNxXsTDnJA6CzIpijA.png" /></figure><h3><strong>Live Data:</strong></h3><p>In Android live data usage is more common now days to update the UI once some data changes. Live data is a observable fields that are observed under specified lifecycle. Like</p><pre>//In Fragment or Activity<br>viewModel.liveDataName.observe(viewLifecycleOwner){ it -&gt;<br><br>}<br><br>//In ViewModel<br><br>viewModelScope.launch(Dispatchers.IO) {<br>      repoImpl.updateStatus(id,code)<br>}</pre><p>Live data in view model is useful to preserve the data while orientation changes and to observe the data.</p><p>Live data observed the data until the corresponding activity or fragment will not destroy.</p><h3><strong>State Flow:</strong></h3><p>Kotlin introduces State flow. State flow is state-holder and observable flows that emit the current and new state. State flow is unaware to lifecycle of activity or fragment so we have to define certain lifecycle state to execute.</p><pre> lifecycleScope.launch {<br>            repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                mainViewModel.authorsStateFlow.collect {<br>                    when (it.status) {<br>                        Status.SUCCESS -&gt; {println(&quot;Shared Flow authors:: &quot;+it.data)}<br>                        Status.ERROR -&gt; {println(&quot;Shared Flow Error:: &quot;+it.message)}<br>                        else -&gt; {}<br>                    }<br>                }<br>            }<br>        }</pre><p>There are some differences between live data and state flow lets check them.</p><h3><strong>LiveData vs StateFlow</strong></h3><ol><li><strong>Immutability:</strong></li></ol><p><strong>Live Data: </strong>LiveData allows mutable data, which means you can modify the data directly. While LiveData itself is observable, you need to be careful to ensure that you don’t accidentally modify the data from multiple threads, which can lead to concurrency issues.</p><p><strong>StateFlow:</strong> StateFlow is designed to work with immutable data. When you emit a new value, it replaces the previous value, and you can’t modify the emitted value directly. This encourages a more functional and reactive programming style.</p><p>2. <strong>LifeCycle Aware:</strong></p><p><strong>Live Data: </strong>Live data is lifecycle aware of activity or fragment lifecycle so it will manage the state according to lifecycle like it knows when the activity or fragment started or destroyed so it observe the data changes until the activity or fragment is in live state.</p><p><strong>StateFlow: </strong>StateFlow flow is coroutine specific so it doesn’t know about the lifecycle of its attached fragment or activity by itself so we have to tell it when to start observing certain data.</p><p>3.<strong> Scope:</strong></p><p><strong>Live Data: </strong>Live Data is android specific so primarily used with android apps.</p><p><strong>StateFlow: </strong>StateFlow is part of the Kotlin Coroutines library and is not Android-specific. It can be used in non-Android Kotlin applications as well.</p><p>4<strong>. Interopability </strong>:</p><p><strong>LiveData</strong>: LiveData is specifically designed for Android and works well with the Android architecture components. It’s tightly integrated with ViewModel and LiveData Observers.</p><p><strong>StateFlow</strong>: StateFlow can be used with Kotlin Coroutines, making it a good choice for apps that use coroutines extensively for asynchronous programming.</p><p><strong>Usage Example of Kotlin State Flow:</strong></p><p>I am following MVVM Pattern.</p><p>Let&#39;s Start with api defining interface.</p><pre>interface ApiInterfaces {<br>    @GET(&quot;getAllBooks&quot;)<br>    suspend fun getBooks():Response&lt;MutableList&lt;BooksResponse&gt;&gt;<br><br>    @GET(&quot;getAllAuthors&quot;)<br>    suspend fun getAllAuthors():Response&lt;MutableList&lt;AuthorsResponseModel&gt;&gt;<br>}</pre><p>In Api Interface i have defined the suspend type function because state flow work well with coroutines.</p><p>In Repository:</p><pre>class Repository @Inject constructor(private val api:ApiInterfaces,private val externalScope: CoroutineScope):BaseRemoteRepo() {<br><br>    fun getBooksData() = flow {<br>        emit(safeApiCall {<br>            api.getBooks()<br>        })<br>    }.flowOn(Dispatchers.IO)<br>    // By using shareIn we can convert a cold flow(flow) to a hot shared flow<br>//        .shareIn(<br>//        scope = externalScope,<br>//        replay = 1,<br>//        started = SharingStarted.WhileSubscribed()<br>    //)<br><br>    fun getAuthorsData() = flow {<br>        emit(safeApiCall {<br>            api.getAllAuthors()<br>        })<br>    }.flowOn(Dispatchers.IO)<br>//        .shareIn(<br>//        scope = externalScope,<br>//        replay = 1,<br>//        started = SharingStarted.WhileSubscribed()<br>   // )<br>}</pre><p>In Repo I called the api function inside a flow and emit the value returned by the function to view model on IO thread.</p><p>I have designed the Base Repo to call functions:</p><pre>abstract class BaseRemoteRepo {<br><br>    suspend fun &lt;T&gt; safeApiCall(apiCall: suspend () -&gt; Response&lt;T&gt;?): NetworkResult&lt;T&gt; {<br>        try{<br>            val response = apiCall.invoke()<br>            if(response != null &amp;&amp; response.isSuccessful){<br>                return NetworkResult.success(response.body())<br>            }<br>            val errorBody = response?.errorBody()?.string()<br>            if (response?.code() == 404) {<br>                    return NetworkResult.error(&quot;Bad Request&quot;)<br>            } else if (!errorBody.isNullOrEmpty()) {<br>                    return NetworkResult.error(errorBody)<br>                }<br><br>        }catch (e: Exception) {<br>            println(e.message)<br>            throw RuntimeException(e)<br>        }<br>        return NetworkResult.loading()<br>    }<br>}</pre><p>In View Model i observed the emitted data from the cold flow defined in repo.</p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(private val repo:Repository): BaseViewModel() {<br> private val mutableStateData= MutableStateFlow&lt;NetworkResult&lt;MutableList&lt;BooksResponse&gt;?&gt;&gt;(NetworkResult.loading())<br> private val authorsData= MutableStateFlow&lt;NetworkResult&lt;MutableList&lt;AuthorsResponseModel&gt;?&gt;&gt;(NetworkResult.loading())<br>   val booksStateFlow:StateFlow&lt;NetworkResult&lt;MutableList&lt;BooksResponse&gt;?&gt;&gt; = mutableStateData<br>   val authorsStateFlow:StateFlow&lt;NetworkResult&lt;MutableList&lt;AuthorsResponseModel&gt;?&gt;&gt; = authorsData<br><br>    fun getBooks(){<br>        viewModelScope.launch {<br>            repo.getBooksData().catch {<br>                mutableStateData.value= it.message?.let { it1 -&gt; NetworkResult.error(it1) }!!<br>            }.collect{<br>                if(it.data != null){<br>                    mutableStateData.value=NetworkResult.success(it.data)<br>                }else{<br>                    mutableStateData.value= it.message?.let { it1 -&gt; NetworkResult.error(it1) }!!<br>                }<br>            }<br>        }<br>    }<br><br>    fun getAllAuthors(){<br>        viewModelScope.launch {<br>            repo.getAuthorsData().catch {<br>             authorsData.value= it.message?.let { it1 -&gt; NetworkResult.error(it1) }!!<br>            }.collect{<br>             if(it.data!=null){<br>                 authorsData.value= NetworkResult.success(it.data)<br>             }<br>             else{<br>                 authorsData.value= it.message?.let { it1 -&gt; NetworkResult.error(it1) }!!<br>             }<br>            }<br>        }<br>    }<br><br>}</pre><p>In activity i have observed the state flow:</p><pre> mainViewModel= ViewModelProvider(this)[MainViewModel::class.java]<br> mainViewModel.getBooks()<br> mainViewModel.getAllAuthors()<br><br>lifecycleScope.launch {<br>    repeatOnLifecycle(Lifecycle.State.STARTED) {<br>        mainViewModel.authorsStateFlow.collect {<br>            when (it.status) {<br>                Status.SUCCESS -&gt; {println(&quot;Shared Flow authors:: &quot;+it.data)}<br>                Status.ERROR -&gt; {println(&quot;Shared Flow Error:: &quot;+it.message)}<br>                else -&gt; {}<br>            }<br>        }<br>    }<br>    repeatOnLifecycle(Lifecycle.State.STARTED) {<br>        mainViewModel.booksStateFlow.collect {<br>            when (it.status) {<br>                Status.SUCCESS -&gt; {println(&quot;Shared Flow Books:: &quot;+it.data)}<br>                Status.ERROR -&gt; {println(&quot;Shared Flow Error:: &quot;+it.message)}<br>                else -&gt; {}<br>            }<br>        }<br>    }<br>}</pre><p>After all we are able to observe the data using state flow.</p><p><strong>Conslusion:</strong></p><p>The choice between StateFlow and LiveData depends on your specific use case and project requirements. StateFlow is a more general-purpose solution, while LiveData is more tightly integrated with Android’s lifecycle and architecture components. If you’re working on an Android project, LiveData is often the preferred choice for managing UI-related data. If you’re working in a pure Kotlin or multi-platform project, StateFlow might be a more natural fit.</p><p><strong><em>Here is the link of github for whole app:</em></strong></p><p><a href="https://github.com/Majid460/StateFlows_Kotlin_Architecture">GitHub - Majid460/StateFlows_Kotlin_Architecture: This repository contains the kotlin state flows and mutable state flows and also describes the data flowing with state flows</a></p><p>Thanks for reading.</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59267a6f2f98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>