<?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 Sandeep Sankla on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Sankla on Medium]]></description>
        <link>https://medium.com/@sandeep.jan19?source=rss-dbe1a4ef468------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CNfGDqo9VXvlO3hM0T9Rjw.jpeg</url>
            <title>Stories by Sandeep Sankla on Medium</title>
            <link>https://medium.com/@sandeep.jan19?source=rss-dbe1a4ef468------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:30:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeep.jan19/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[From a Real Business Problem to a Production Android App — Running Live in a Restaurant]]></title>
            <link>https://medium.com/@sandeep.jan19/from-a-real-business-problem-to-a-production-android-app-running-live-in-a-restaurant-b6de208df48a?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6de208df48a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[software-engineering-job]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 09:10:52 GMT</pubDate>
            <atom:updated>2026-08-11T09:10:52.629Z</atom:updated>
            <content:encoded><![CDATA[<p>How I built a restaurant order management system used every day at Tandoori Tadka Restaurant — and what production taught me about Android engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmJlzCjYjchRPbJqTCu_ew.png" /></figure><p>Most portfolio projects showcase technical skills through sample apps. This one manages real customer orders every single day.</p><p>While running Tandoori Tadka Restaurant, I experienced firsthand how inefficient order handling affected day-to-day operations. Existing POS solutions were either too expensive, too complex, or didn’t match the workflow of a small restaurant.</p><p>So instead of adapting the business to fit the software, I built software around the business.</p><p>Introducing <strong>RestaurantOrderTakingApp</strong> — a production-ready Android application designed to streamline restaurant operations with a modern, scalable architecture.</p><h3>The Business Challenges</h3><ul><li>Reception and kitchen coordination relied entirely on verbal communication, creating confusion during peak hours.</li><li>Orders containing both Kitchen and Tandoor items were difficult to track independently.</li><li>End-of-day reconciliation for Cash, UPI, and Udhaar (credit) was completely manual.</li><li>Network interruptions affected menu availability and disrupted operations.</li></ul><p>These weren’t hypothetical problems from a product spec — they were things I watched go wrong on the floor, during a dinner rush, with real customers waiting.</p><h3>The Solution</h3><p><strong>Role-Based Devices</strong> — Each tablet is securely configured as either Reception or Kitchen (PIN-protected), so users only access the functionality relevant to their role. Kitchen devices never expose administrative controls.</p><p><strong>Station-Aware Order Routing</strong> — Every menu item is automatically routed to its preparation station (Kitchen or Tandoor). An order is marked complete only after all its stations finish their assigned items.</p><p><strong>Workflow-Oriented Design</strong> — Supports both Dine-In and Takeaway workflows while keeping the experience simple for staff. Both share the same backend.</p><p><strong>Integrated Payment Management</strong> — Tracks Cash, UPI, and Udhaar, with daily reports for collections and outstanding balances.</p><p><strong>Real-Time Kitchen Notifications</strong> — New orders instantly trigger a ringtone, a voice announcement (“Naya Order Aaya”), and live queue updates on the kitchen device.</p><p><strong>Offline-First Architecture</strong> — Room acts as the local source of truth; Firebase Firestore syncs whenever connectivity is available — so the restaurant keeps operating even during network outages.</p><h3>Technical Deep Dive: Station-Based Order Routing</h3><p>The single most important design decision was <strong>station-level order management</strong> — and it’s the part I’m asked about most, so it’s worth unpacking.</p><p><strong>The problem:</strong> A single order — say, <em>Afghani Chap</em> (Tandoor) + <em>Veg Noodles</em> (Kitchen) — isn’t one unit of work. It’s two, prepared by two different teams on two different devices, at two different speeds. Treating the order as one atomic thing meant the kitchen couldn’t see “their” items clearly, and reception had no reliable way to know when the <em>whole</em> order was actually done.</p><p><strong>The model:</strong> Instead of tracking status at the order level, I track it at the <strong>order-item level</strong>, with each item carrying its own station and status.</p><pre>Order<br> ├─ OrderItem(name=&quot;Afghani Chap&quot;, station=TANDOOR, status=PREPARING)<br> ├─ OrderItem(name=&quot;Veg Noodles&quot;,  station=KITCHEN, status=READY)<br> └─ OrderItem(name=&quot;Paneer Momos&quot;,  station=KITCHEN, status=PREPARING)</pre><p>Each station device queries only the items assigned to it:</p><pre>fun observeStationItems(station: Station): Flow&lt;List&lt;OrderItem&gt;&gt; =<br>    orderItemDao.observeByStation(station.name)<br>        .map { items -&gt; items.filter { it.status != DELIVERED } }</pre><p><strong>Deriving order completion:</strong> The order’s overall status is never set directly — it’s <em>derived</em> from its items. This keeps the source of truth in one place and avoids the classic bug where an order is marked “ready” while an item is still cooking.</p><pre>val orderStatus: OrderStatus = when {<br>    items.all { it.status == READY } -&gt; READY<br>    items.any { it.status == PREPARING } -&gt; PREPARING<br>    else -&gt; RECEIVED<br>}</pre><p>Because everything flows through Flow/StateFlow, the moment the Tandoor device marks its item ready, the derived order status recomputes and reception&#39;s screen updates — no manual refresh, no polling.</p><p>The payoff: unrelated prep tasks are fully decoupled, each team sees only what it owns, and “is this order done?” always has one correct, computed answer.</p><h3>Technical Deep Dive: Offline-First Sync</h3><p>A restaurant can’t stop taking orders because the WiFi dropped. So offline isn’t a fallback mode — it’s the <em>default</em> mode.</p><p><strong>Room is the single source of truth.</strong> The UI never reads from the network directly; it always observes Room. Firestore is treated as a sync layer on top, not the primary data store.</p><p>The flow for any write (new order, status change, payment) is:</p><ol><li>Write to Room immediately → UI updates instantly (optimistic, always available).</li><li>Mark the record as pendingSync = true.</li><li>A sync worker pushes pending records to Firestore whenever connectivity returns, then clears the flag.</li><li>Incremental sync pulls only records changed since the last successful sync timestamp — no full re-downloads.</li></ol><p>This gives two things at once: <strong>responsiveness</strong> (every action is local-first, so there’s zero network latency in the UI) and <strong>reliability</strong> (nothing is lost during an outage — it just syncs later). Menu data is cached the same way, so even a fresh app launch on a dead connection still shows the full menu.</p><h3>Technology Stack</h3><p>Kotlin · Jetpack Compose · Clean Architecture · MVVM · Hilt · Room · Firebase Firestore · Coroutines · Flow / StateFlow · JUnit 5 · MockK</p><h3>What Building for Production Taught Me</h3><ul><li>Great software starts with understanding real business problems — not just writing clean code.</li><li>Architecture should evolve from operational needs, not theoretical patterns.</li><li>Offline capability is a reliability requirement, not an optional feature.</li><li>The most valuable lessons come from observing real users, real workflows, and real edge cases — the ones that never show up in a dev environment.</li></ul><h3>Links</h3><p>🔗 <strong>Source code:</strong> <a href="https://github.com/sandeepsankla/RestaurantOrderTakingApp">https://github.com/sandeepsankla/RestaurantOrderTakingApp</a></p><p>If you’re building scalable Android products or hiring Android engineers, I’d love to connect and hear your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6de208df48a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your app’s UI is no longer the only entry point.]]></title>
            <link>https://medium.com/@sandeep.jan19/your-apps-ui-is-no-longer-the-only-entry-point-d246ec32bbff?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/d246ec32bbff</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Tue, 19 May 2026 12:35:32 GMT</pubDate>
            <atom:updated>2026-05-19T12:35:32.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1b1tI0z_7ddt_vvQw-aaIA.png" /></figure><p>Your app’s UI is no longer the only entry point. Android 17 lets Gemini call your app’s capabilities in the background through a new API surface called AppFunctions — without ever launching an Activity. And if early signals from the developer preview are anything to go by, apps that don’t expose AppFunctions are likely to lose ground in any flow where Gemini can fulfill the user’s intent through a competitor that does. Not with a warning. Not with a migration notice. Just gradually, in the flows you can’t see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-rjfAtqgpxcgH7jhGAuDA.png" /></figure><p>I’ve been writing Android since the Jelly Bean days — long enough to have lived through AsyncTask, Fragments, RxJava, Coroutines, and the slow migration to Compose. Some shifts looked bigger than they were. This one feels like it’ll matter more than App Actions ever did. And the window to experiment with it sensibly is right now, before the Pixel/Galaxy rollout this summer starts setting defaults.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxZyfyj02E4RSM-5HcdLPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORbR2VuYTiZxVwi900lumw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4bujcYrlQIfyJUVC_x3BA.png" /></figure><p>Google is positioning Android as an <strong>Intelligence System</strong>, not just an operating system. That’s not pure marketing — it’s an architectural direction. Gemini is moving from being a chatbot you open in an app to being an OS-level layer that decides which app gets called, what data it needs, and whether the UI gets opened at all. The metric we’ve optimized for — “Is the user in my app?” — is starting to give ground to a harder one: “Did my app help the user finish the task?”</p><p>Android 17 handles this through two tracks. The first is <strong>UI Automation</strong> — zero code changes, Gemini navigates your app visually using accessibility APIs. It’s the free baseline, and it’s inherently fragile (it breaks on redesigns and depends on screen reachability). The second is <strong>AppFunctions</strong> — structured, on-device function calls that Gemini can discover, understand, and execute directly. Apps that invest in the second track will likely have a more durable position in the agent layer, but it’s worth being honest: nobody has shipped this at scale yet, and the rollout still has open questions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m96TjcuVZl66jCSoB06DSw.png" /></figure><p>Before we write a line of code, get the mental model right — because I’ve seen intelligent developers confuse AppFunctions with three things they are not: they are not App Actions (the old intent-based approach), they are not deep links with natural language wrappers, and they are absolutely not annotated methods you bolt onto your existing ViewModel.</p><p>AppFunctions are self-describing, OS-indexed, on-device tools that the assistant layer can discover and call autonomously. The closest analogy in the current ecosystem is the <strong>Model Context Protocol (MCP)</strong>. MCP lets server-side LLMs connect to tools via HTTP. AppFunctions does the same thing for your Android app, locally, with the OS acting as the broker. Your app becomes a microservice the agent can call. The user never sees your launcher icon — but your service still solved their problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9X9qwUkCL5jLjrlrR5MOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_vX3hXUH-3NEcEom3HUqw.png" /></figure><p>The developers who will regret AppFunctions are the ones who treat it as a feature to tack on. The right approach: AppFunctions are a separate entry point into your domain layer, sitting alongside your UI layer, sharing the same business logic, touching none of the same ViewModel concerns.</p><h3>Step 1: Dependencies</h3><pre>build.gradle.kts (app)<br>Kotlin DSL<br>// AppFunctions core + KSP compiler<br>// Note: alpha APIs can change — track releases at d.android.com/appfunctions<br>dependencies {<br>    implementation(&quot;androidx.appfunctions:appfunctions-core:1.1.0-alpha05&quot;)<br>    ksp(&quot;androidx.appfunctions:appfunctions-compiler:1.1.0-alpha05&quot;)<br>}<br><br>// KSP plugin — required in plugins block<br>plugins {<br>    id(&quot;com.google.devtools.ksp&quot;) version &quot;2.0.21-1.0.28&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eeJqchJkOpLkJm0aYjuTg.png" /></figure><pre>import androidx.appfunctions.AppFunction<br>import androidx.appfunctions.AppFunctionContext<br><br>/**<br> * AppFunction boundary: translates an agent call into a domain action.<br> * Contains NO business logic — delegates entirely to the UseCase layer.<br> * This is the same UseCase your ViewModel already calls.<br> */<br>class WorkoutFunctions @Inject constructor(<br>    // Constructor injection — same UseCase your ViewModel already has<br>    private val startWorkoutUseCase: StartWorkoutUseCase,<br>    private val purchaseUseCase: PurchasePlanUseCase<br>) {<br><br>    /**<br>     * Starts a workout tracking session.<br>     * &quot;Track my 5km run&quot; → Gemini resolves to this function.<br>     *<br>     * Parameter names are read by Gemini. Be explicit.<br>     * &quot;distanceKm&quot; &gt; &quot;distance&quot; &gt; &quot;d&quot;. Always.<br>     */<br>    @AppFunction<br>    suspend fun startWorkout(<br>        context: AppFunctionContext,<br>        distanceKm: Double,<br>        workoutType: String   // &quot;run&quot;, &quot;cycle&quot;, &quot;swim&quot; — Gemini infers this<br>    ): String = when (val result = startWorkoutUseCase.execute(distanceKm, workoutType)) {<br>        is WorkoutResult.Success       -&gt; &quot;Tracking your ${distanceKm}km ${workoutType}. GPS locked.&quot;<br>        is WorkoutResult.GpsUnavailable -&gt; &quot;GPS signal weak. Try moving outside first.&quot;<br>        is WorkoutResult.AlreadyRunning -&gt; &quot;You already have an active session running.&quot;<br>    }<br><br>    // requiresConfirmation = true pauses execution for user approval<br>    // Use this for purchases, deletions, and any irreversible action<br>    @AppFunction(requiresConfirmation = true)<br>    suspend fun purchaseTrainingPlan(<br>        context: AppFunctionContext,<br>        planName: String,<br>        priceInRupees: Double<br>    ): String {<br>        val result = purchaseUseCase.execute(planName, priceInRupees)<br>        return if (result.success) &quot;${planName} purchased for ₹${priceInRupees}.&quot;<br>               else &quot;Purchase failed: ${result.errorMessage}&quot;<br>    }<br>}</pre><h3>Step 3: The dual-entry architecture</h3><p>This is the diagram I wish someone had shown me during developer preview. Your codebase now has two entry points into the same domain layer. Both are first-class citizens. Neither owns the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8f7hTeMp3lW3Q2mhtsXRQ.png" /></figure><p>The Compose UI goes through the ViewModel as it always has. The AppFunction skips the ViewModel entirely and calls the UseCase directly. Both produce the same result because they share the same business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cX3uXhSTUQxUw2bhfEydTQ.png" /></figure><p>I’m giving this its own section because the failure mode is invisible. If the model can’t understand what your function does from its name and parameter names, it won’t call it. It won’t throw an error. It won’t log a warning. It will just not call it — and your competitor whose function is named better will get the traffic. You’ll never know you were an option.</p><p>The KSP compiler generates natural language descriptions for the <strong>appfunctions.json</strong> manifest from your identifiers and KDoc comments. This is both the elegance and the responsibility. The assistant reads the manifest. You are, in effect, writing an API contract for an LLM. Write for the model, not for your autocomplete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQwsg0Tz2D4peANx9M8xwg.png" /></figure><p>The rule is simple: function names are verb-noun pairs (startWorkout, sendMessage, bookAppointment). Parameter names are full, unambiguous nouns (recipientEmailAddress not email, deliveryAddressLine1 not addr1). Add KDoc comments — the compiler includes them in the manifest and they significantly improve intent matching on complex or domain-specific operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3OwSsKfxKIBYYFQ5uLYRQ.png" /></figure><p>Android Studio’s 2026 release ships with an AppFunction Inspector that deserves more attention than the docs give it. Three features that will save you real debugging time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaZ0Kenge3_3N7UjtMiD8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOMu1YHp7SaufauB134fzw.png" /></figure><p>I’d be doing you a disservice if I sold this as a no-risk bet. Here’s the honest engineering view of what could go sideways, and how to think about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQ_2ZpxnjYVJ8iJtugVgzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erskU8L2DLbx30BFGJ2Fyw.png" /></figure><p>The first question every PM asks when you propose this is some variation of “Wait, that sounds like a massive privacy risk.” It’s a fair question. The answer is more reassuring than you’d expect, and understanding the architecture helps you make the case.</p><p>Every AppFunction executes on-device, in your app’s process, with your app’s permissions. Not on Google’s servers. Not in the cloud. User data involved in a function call never leaves the device. This matters enormously for GDPR compliance, data residency requirements, and the increasingly sophisticated privacy expectations of users in regulated markets.</p><p>For sensitive operations — purchases, data deletion, message sending — use @AppFunction(requiresConfirmation = true). The runtime pauses execution and surfaces a native confirmation UI before proceeding. Users can review the capability manifest at any time in device settings and can revoke per-app AppFunction permissions individually. The permission model is more granular than most notification permission systems we&#39;ve shipped against.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym5hAhchpOQGNCu0A85Wlw.png" /></figure><p>Gemini is likely to become a meaningful interaction layer for a significant share of Android users over the next 18 months — exactly how much is uncertain, but the direction looks clear. Apps that expose AppFunctions become first-class citizens in that layer. Apps that don’t will, in many flows, either get skipped (if another app covers the use case) or routed through UI automation that’s brittle by design. The investment is modest: one well-architected function class, a few hours in the Agent Simulator, one set of unit tests. The potential return is a new engagement surface that doesn’t require app opens or onboarding friction. Even if AppFunctions evolves significantly during the alpha period, the architectural extraction work (UseCase separation, clean domain boundaries) pays dividends regardless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Pq_Xpsmi1MndaTjhcRN1A.png" /></figure><p>Before any AppFunction goes to code review, run it against this list. I’ve seen every one of these in the wild during the developer preview period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUeYDKnohfAC6xHtF9DFAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HP0pVGzNtON0nrdQ5WIMQ.png" /></figure><p>I have been wrong about paradigm shifts before. I was late to Compose. I underestimated Coroutines at first. So I’m not asking you to take this on faith — I’m suggesting you take it seriously enough to spend a sprint on it. The “headless app” pattern is in developer preview today and reaching Pixel and Galaxy devices this summer. That’s not speculative; that’s a calendar.</p><p>Teams that treat AppFunctions as a real architectural concern in the next quarter will be better positioned eighteen months from now — partly because they’ll be integrated, but mostly because the architectural work itself (UseCase extraction, clean domain boundaries, testable function classes) makes the codebase healthier regardless of how the agent layer evolves. Teams that wait will eventually catch up, but probably with more rework than they’d want.</p><p>The framing that actually matters here is simple: <strong>Android apps are becoming capabilities, not destinations</strong>. The icon doesn’t disappear. It just stops being the only way users reach you. Build for both.</p><h3>References &amp; Further Reading</h3><p>Official Documents</p><p><strong>Android AppFunctions overview</strong> — d.android.com/appfunctions<br><strong>AppFunctions API reference (Jetpack)</strong> — developer.android.com/reference/androidx/appfunctions<br><strong>Android 17 platform changes</strong> — developer.android.com/about/versions/17<br><strong>Android Studio Ladybug release notes</strong> — developer.android.com/studio/releases<br><strong>Model Context Protocol (for the MCP analogy)</strong> — modelcontextprotocol.io<br><strong>Google I/O 2026 — Agents on Android session</strong> — search &quot;Google I/O 2026 AppFunctions&quot; on YouTube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24RKIQNx3SiCxDSm7izgag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4T-rksqHsoxymCyeWQS6Kg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d246ec32bbff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RAG in Android]]></title>
            <link>https://medium.com/@sandeep.jan19/building-rag-in-android-7812eaf7bfbb?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/7812eaf7bfbb</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 12:53:55 GMT</pubDate>
            <atom:updated>2026-04-18T12:53:55.375Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a search feature that actually understands what users mean</em></p><p><strong>I hit a wall about six months into building my Smart Summary App. </strong>Users were saving dozens of summaries — cab bookings, restaurant recommendations, weather notes — and then couldn’t find them again. The search box was useless.</p><p>The problem wasn’t the UI. The problem was that I was using a standard Room query with LIKE, and it only matched exact words. A user searching for “taxi” would miss a summary that said “cab”. A search for “food” would miss “restaurant”.</p><p>That’s when I started digging into <strong>RAG — Retrieval-Augmented Generation</strong>. This post is what I wish someone had explained to me before I spent two weeks figuring it out.</p><h3>The core problem with LIKE queries</h3><p>Here’s a query I had in production:</p><pre>@Query(&quot;SELECT * FROM summaries WHERE text LIKE :query&quot;)<br>suspend fun search(query: String): List&lt;SummaryEntity&gt;<br><br>// Saved summary: &quot;Taxi service available 24/7&quot;<br>// User types: &quot;cab booking&quot;<br>// Result: empty list ❌</pre><p>The database is not being dumb here. It is doing exactly what you told it to do — check if the word ‘cab’ appears in the text. It does not. So it returns nothing.</p><p>#LIKE queries are fine for filtering structured data. They fall apart the moment users start typing naturally, using synonyms, or searching by intent rather than exact phrase.</p><p><em>The fix is not a better LIKE query. The fix is changing how you store and search text entirely.</em></p><h3>What RAG actually is (without the jargon)</h3><p>RAG stands for Retrieval-Augmented Generation. Ignore the name for a second — here is what it actually does:</p><ul><li><strong>Retrieval: </strong>Find content that is <strong>meaningfully similar</strong> to the query — not just word-matched</li><li><strong>Augmented: </strong>Pass that retrieved content to an AI model as extra context</li><li><strong>Generation: </strong>The AI uses that context to give a much better answer</li></ul><p>Think of how you prepare for a meeting. You do not memorise every document your company has ever written. You search for the relevant ones, read them, then walk into the meeting informed. RAG does the same thing — retrieves what is relevant, then generates a response based on it.</p><p>For my Smart Summary App, this meant: when a user searches “I need a ride from the airport”, the app first finds the most semantically similar saved summaries, then passes them to Claude as context.</p><h3>How AI reads text — vector embeddings</h3><p>Before RAG can work, you need a way to convert text into something you can compare mathematically. That is what <strong>vector embeddings</strong> are.</p><p>An embedding model takes a piece of text and outputs a list of numbers — usually 768 or 1536 of them. These numbers capture the meaning of the text in a way that similar texts produce similar numbers.</p><pre>&quot;King&quot;   → [0.82, -0.31, 0.67, 0.14 ... ]  // 768 numbers<br>&quot;Queen&quot;  → [0.79, -0.28, 0.61, 0.19 ... ]  // nearly identical<br>&quot;Banana&quot; → [-0.12, 0.54, -0.43, 0.88 ... ] // completely different</pre><p>The model was never explicitly told that King and Queen are related. It learned this from patterns in enormous amounts of text. You can even do arithmetic: <em>King − Man + Woman ≈ Queen</em>. The numbers encode semantic relationships.</p><h3>Measuring similarity — cosine similarity</h3><p>Once you have two vectors, you measure how similar they are by calculating the cosine of the angle between them. The result is a score from -1 to 1:</p><ul><li>1.0 — identical meaning</li><li>0.6 to 0.9 — closely related</li><li>0.0 — unrelate</li><li>-1.0 — opposite meaning</li></ul><p>Here are real numbers from my app:</p><pre>Query: &quot;How to book a cab?&quot;<br>&quot;Taxi booking process&quot; → 0.628 ✅ related<br>&quot;Recipe for biryani&quot; → 0.154 ❌ unrelated</pre><p>No word in the query appears in “Taxi booking process”. But the model knows they are about the same thing. That is the shift.</p><h3>The full pipeline — visualised</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocwadPsOVBDPX5Iwu1OS0Q.png" /></figure><h3>Traditional DB vs Vector Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC1k36_KEfApNFNjOtARsw.png" /></figure><h3>Building it in Android — the actual code</h3><p>I used the Gemini text-embedding-004 model via REST API, Room DB for storage, and pure Kotlin for cosine similarity. No fancy vector DB needed to get started.</p><h3>1. The Room entity</h3><p>The key addition is storing the embedding as a JSON string, plus metadata fields that let you pre-filter before running similarity search:</p><pre>@Entity(<br>    tableName = &quot;summaries&quot;,<br>    indices = [<br>        Index(value = [&quot;category&quot;]),<br>        Index(value = [&quot;language&quot;]),<br>        Index(value = [&quot;category&quot;, &quot;language&quot;])<br>    ]<br>)<br>data class SummaryEntity(<br>    @PrimaryKey(autoGenerate = true) val id: Int = 0,<br>    val text: String,<br>    val embedding: String,   // JSON — List&lt;Float&gt;<br>    val category: String,    // &quot;transport&quot;, &quot;food&quot;, &quot;weather&quot;<br>    val language: String,    // &quot;en&quot;, &quot;hi&quot;<br>    val createdAt: Long = System.currentTimeMillis()<br>)</pre><p><em>The indices on category and language are important. They let Room filter down to a small subset before cosine similarity runs — otherwise you are comparing every record in the table on every search.</em></p><h3>2. Getting the embedding</h3><pre>suspend fun getEmbedding(text: String, apiKey: String): List&lt;Float&gt; {<br>    return withContext(Dispatchers.IO) {<br>        val url = URL(&quot;https://generativelanguage.googleapis.com/v1beta/models/<br>            text-embedding-004:embedContent?key=$apiKey&quot;)<br>        val connection = (url.openConnection() as HttpURLConnection).apply {<br>            requestMethod = &quot;POST&quot;<br>            setRequestProperty(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>            doOutput = true<br>        }<br>        val body = JSONObject().apply {<br>            put(&quot;model&quot;, &quot;models/text-embedding-004&quot;)<br>            put(&quot;content&quot;, JSONObject().apply {<br>                put(&quot;parts&quot;, JSONArray().apply {<br>                    put(JSONObject().apply { put(&quot;text&quot;, text) })<br>                })<br>            })<br>        }.toString()<br>        connection.outputStream.use { it.write(body.toByteArray()) }<br>        val response = connection.inputStream.bufferedReader().readText()<br>        val values = JSONObject(response)<br>            .getJSONObject(&quot;embedding&quot;)<br>            .getJSONArray(&quot;values&quot;)<br>        List(values.length()) { i -&gt; values.getDouble(i).toFloat() }<br>    }<br>}</pre><h3>3.Cosine similarity in Kotlin</h3><pre>fun cosineSimilarity(a: List&lt;Float&gt;, b: List&lt;Float&gt;): Float {<br>    val dot  = a.zip(b).sumOf { (x, y) -&gt; (x * y).toDouble() }<br>    val magA = Math.sqrt(a.sumOf { (it * it).toDouble() })<br>    val magB = Math.sqrt(b.sumOf { (it * it).toDouble() })<br>    return (dot / (magA * magB)).toFloat()<br>}</pre><h3>4. Putting it together — filtered similarity search</h3><pre>suspend fun findSimilar(<br>    queryText: String,<br>    apiKey: String,<br>    dao: SummaryDao<br>): List&lt;Pair&lt;SummaryEntity, Float&gt;&gt; {<br>    val queryEmbedding = getEmbedding(queryText, apiKey)<br>    val category = detectCategory(queryText)<br><br>    // Room index kicks in here — only scans matching category<br>    val candidates = dao.getByCategory(category)<br>        .ifEmpty { dao.getAll() }<br><br>    return candidates<br>        .map { entity -&gt;<br>            val stored: List&lt;Float&gt; = Gson().fromJson(entity.embedding, ...)<br>            Pair(entity, cosineSimilarity(queryEmbedding, stored))<br>        }<br>        .sortedByDescending { it.second }<br>        .take(3)<br>}</pre><h3>Does it actually work?</h3><p>Short answer: yes, noticeably.</p><p>After saving four test summaries — a cab booking note, a taxi availability note, a restaurant note, and a weather note — I ran this query:</p><pre>findSimilar(&quot;I need a ride from airport&quot;)<br><br>// Results:<br>0.91 — &quot;Book a cab from airport to hotel&quot;   ✅<br>0.79 — &quot;Taxi service available 24/7&quot;         ✅<br>0.21 — &quot;Best biryani in Gurugram&quot;            ❌ (correctly low)<br>0.08 — &quot;Weather forecast Delhi NCR&quot;          ❌ (correctly low)</pre><p>The query used the word <em>“ride”</em>. Neither of the matching summaries contains that word. The model understood intent, not just vocabulary. That is the entire point.</p><h3>Which vector DB should you use?</h3><p>Honest answer — it depends on where you are in the project.</p><pre>findSimilar(&quot;I need a ride from airport&quot;)<br><br>// Results:<br>0.91 — &quot;Book a cab from airport to hotel&quot;   ✅<br>0.79 — &quot;Taxi service available 24/7&quot;         ✅<br>0.21 — &quot;Best biryani in Gurugram&quot;            ❌ (correctly low)<br>0.08 — &quot;Weather forecast Delhi NCR&quot;          ❌ (correctly low)</pre><p>Great on backend, not Android.</p><p>For most Android projects just getting started with semantic search, Room plus a cosine similarity function is all you need. You avoid a new dependency, the setup is twenty minutes, and you can always migrate to ObjectBox later when your dataset grows.</p><h3>What this setup cannot do (yet)</h3><p>I want to be upfront about the current limitations:</p><p><em>None of these are blockers for shipping. They are known tradeoffs, not unknown bugs. Shipping something that works well enough today beats perfecting something that never ships.</em></p><h3>Final thoughts</h3><p>RAG is one of those patterns that sounds complicated until you actually build it — then it feels obvious. The hard part is not the cosine similarity math or the API call. The hard part is understanding why your existing search is broken and what problem you are actually solving.</p><p>If your app stores any kind of user-generated content — notes, summaries, messages, logs — and users need to find things again later, you probably need this. A LIKE query is not good enough once users start relying on your app seriously.</p><p>The full implementation is part of my <strong>Smart Summary App</strong> — an Android app that combines ML Kit OCR, translation, on-device and cloud summarization, and now semantic search. The code is on GitHub if you want to dig into it.</p><p><strong>Sandeep Sankla | </strong>Senior Android Engineer · Gurugram, India | github.com/sandeepsankla</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7812eaf7bfbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Senior to Architect: 10 Clean Architecture Trade-offs That Define Your Level]]></title>
            <link>https://medium.com/@sandeep.jan19/from-senior-to-architect-10-clean-architecture-trade-offs-that-define-your-level-9a9bfb954d84?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9bfb954d84</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-cleanarchitecture]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 17:10:34 GMT</pubDate>
            <atom:updated>2026-01-29T21:51:02.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qs_3GSOHAdhZk6F6no1LxA.png" /></figure><p>Most engineers learn Clean Architecture as a set of rules.<br>Senior engineers follow those rules.<br>Architects know when the rules are helping — and when they are silently slowing the team down.</p><p>This article explores <strong>10 deceptively simple Clean Architecture questions</strong><br>that quietly expose how you think about trade-offs, change, and long-term impact — <br><strong>the real signals interviewers look for beyond “clean code.</strong>”</p><p>This article is a continuation of <a href="https://medium.com/@sandeep.jan19/mastering-kotlin-coroutines-deep-dive-interview-questions-for-senior-engineers-41557dcca5ec"><strong>Mastering Kotlin Coroutines: Deep-Dive Interview Questions for Senior Engineers</strong>.</a></p><p>Before jumping into the interview questions, I recommend revisiting the coroutine fundamentals covered in my <a href="https://github.com/sandeepsankla/android-interview-deep-dive/tree/main/app/src/main/java/com/example/androidinterviewdeepdive/cleanArchitecture"><strong>GitHub</strong></a> notes.</p><h3>1️⃣ Can an Entity contain business logic?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“No, entities are just data classes or POJOs.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br><strong>Yes.</strong> Entities can — and should — contain <strong>Enterprise Business Rules</strong>.</p><h3>Why?</h3><p>Enterprise rules are:</p><ul><li>always true</li><li>stable over time</li><li>independent of UI, database, API, or application flow</li></ul><p><strong>Example:</strong></p><pre>fun isAdult(): Boolean = age &gt;= 18</pre><p>This rule would exist even if the app, database, or UI disappeared.</p><h3>The Boundary</h3><ul><li><strong>Entities</strong> represent <strong>Business Truth</strong></li><li><strong>UseCases</strong> represent <strong>Business flow.</strong></li></ul><p><strong>Business Truth vs. Business flow (example)</strong></p><ul><li>“GST is 18%” → <strong>Business truth</strong></li><li>“Apply GST after discount during checkout” → <strong>Business Process/Flow</strong></li></ul><h3>2️⃣ Where should a discount rule live: Entity or UseCase?</h3><blockquote><em>“If cart value &gt; ₹1000, give 10% discount.”</em></blockquote><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Put it in the UseCase to keep the Entity clean.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br>It depends on <strong>rule stability</strong>.</p><h3>Two cases:</h3><ul><li><strong>Core pricing rule</strong> (e.g., tax rate, permanent pricing logic) → <strong>Entity</strong></li><li><strong>Context-dependent rule</strong> (festival, campaign, coupon, A/B test) → <strong>UseCase</strong></li></ul><h3>Architect’s Insight</h3><p>A strong design often looks like this:</p><ul><li>Entity holds the <em>facts</em></li><li>UseCase orchestrates the <em>decision</em></li><li>Strategy (e.g., DiscountPolicy) is injected</li></ul><p>Entities express rules.<br>UseCases decide <strong>when and how</strong> to apply them.</p><h3>3️⃣ Why do dependencies always point inward in Clean Architecture?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Because Clean Architecture says so.”</em></blockquote><p><strong>The “Lead / Architect” Answer:</strong><br>Because <strong>business rules must not depend on details</strong> — details must depend on business rules.</p><h3>What “Inward Dependency” Really Means</h3><p>Inner layers (Domain) define:</p><ul><li>what the business <strong>is</strong></li><li>how the business <strong>works</strong></li></ul><p>Outer layers (UI, DB, Network) define:</p><ul><li>how the business is <strong>delivered</strong></li><li>how data is <strong>stored or shown</strong></li></ul><blockquote><strong><em>What the system does must not depend on how it is delivered.</em></strong></blockquote><h3>Direction Explained</h3><pre>UI → UseCase → Entity<br>Data → UseCase → Entity</pre><ul><li>UI depends on Domain</li><li>Data depends on Domain</li><li><strong>Domain depends on nothing</strong></li></ul><h3>Important Clarification</h3><p>❌ Inward dependency does <strong>not</strong> mean data only flows inward<br>✅ Data can flow both ways — <strong>dependencies cannot</strong></p><p>This is enforced using:</p><ul><li>interfaces</li><li>dependency inversion</li><li>DI frameworks</li></ul><h3>4️⃣ Why should a ViewModel not hold Context or R.string?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Memory leaks and broken unit tests.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br>It’s about <strong>architecture survival</strong>.</p><h3>The Real Problems</h3><ul><li>Context couples ViewModel to Android</li><li>JVM testing becomes harder</li><li>Localization logic leaks into business logic</li></ul><h3>Correct Responsibility Split</h3><ul><li><strong>ViewModel</strong> → exposes <em>what</em> to show (state, IDs)</li><li><strong>UI layer</strong> → decides <em>how</em> to show it (resources)</li></ul><blockquote><em>ViewModels manage </em><strong><em>state</em></strong><em>, not </em><strong><em>Android APIs</em></strong><em>.</em></blockquote><h3>5️⃣ How many mappers are required in a Clean Architecture app?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“One mapper per layer.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br><strong>As many as needed to protect boundaries.</strong></p><h3>The Rule</h3><p>Whenever data <strong>crosses a layer boundary</strong>, a mapper may be required.</p><p>Typical real-world flow:</p><ul><li>DTO → Domain</li><li>Entity → Domain</li><li>Domain → Entity</li><li>Domain → UI Model</li></ul><h3>Litmus Test</h3><blockquote><em>If a backend JSON change breaks your UI code, you failed the mapper test.</em></blockquote><p>This reinforces <em>why</em> mappers exist, not just <em>when</em>.</p><h3>6️⃣ Why not use a single model across API, DB, Domain, and UI?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Because Clean Architecture says so.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br>Because <strong>change does not propagate evenly</strong>.</p><h3>Reality Check</h3><ul><li>APIs change due to backend evolution</li><li>Databases change for performance or migration</li><li>UI changes for UX</li><li>Domain must remain stable</li></ul><p>Using one model everywhere creates <strong>tight coupling</strong>.</p><blockquote><strong><em>Architect’s mantra:</em></strong><em><br></em>Duplication is cheaper than coupling.</blockquote><h3>7️⃣ If Clean Architecture is so good, why don’t startups use it?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“They’re lazy or don’t know best practices.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br>Because startups optimize for <strong>speed of learning</strong>, not <strong>cost of change</strong>.</p><h3>Why?</h3><ul><li>Early startups may delete the app entirely</li><li>Over-architecting before validation is wasteful</li></ul><blockquote><em>Architecture is a long-term investment.<br>Startups delay that investment until survival is proven.</em></blockquote><h3>8️⃣ Where do cross-cutting concerns (Analytics, Auth, Logging) live?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Just call the SDK from the UseCase.”</em></blockquote><p><strong>The “Lead” Answer:</strong></p><ul><li><strong>Interface</strong> → Domain</li><li><strong>Implementation</strong> → Data / Infrastructure</li></ul><h3>Why This Matters</h3><p>Define AnalyticsTracker in Domain.<br>Implement it using Firebase, Mixpanel, etc., in Data.</p><p>UseCases depend on <strong>interfaces</strong>, not SDKs.</p><blockquote><em>Cross-cutting concerns should </em><strong><em>observe</em></strong><em> business logic — never </em><strong><em>drive</em></strong><em> it.</em></blockquote><h3>9️⃣ What breaks first when Clean Architecture is violated?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Unit tests or performance.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br><strong>Cost of change and team velocity.</strong></p><h3>Symptoms</h3><ul><li>Small changes touch many unrelated files</li><li>Developers fear refactoring</li><li>Bugs appear in unrelated features</li></ul><blockquote><em>Architecture doesn’t crash apps.<br>It slowly makes teams unable to move.</em></blockquote><h3>🔟 Backend changes completely (Firebase → OAuth). Which layers change?</h3><p><strong>The “Senior” Answer:</strong></p><blockquote><em>“Data layer and maybe Repository.”</em></blockquote><p><strong>The “Lead” Answer:</strong><br><strong>Only the Data layer.</strong></p><h3>Why This Matters</h3><p>This is the ultimate <strong>litmus test</strong> of Clean Architecture.</p><p>If UseCases or ViewModels change because the backend changed, your abstraction has leaked.</p><h3><em>Architecture is not about clean code.<br>It’s about </em><strong><em>keeping teams fast, safe, and confident as systems grow</em></strong><em>.</em></h3><h3>✅ Final Note</h3><p>If this article helped you see Clean Architecture beyond rules and layers,<br> <strong>please give it a clap</strong> — it helps more engineers discover and learn from it.</p><p>💬 <strong>I’d love to hear from you:</strong><br> What Clean Architecture interview question do <em>you</em> think must be part of every senior or lead-level discussion?</p><p><strong>Drop your question in the comments 👇</strong><br>Let’s build a practical, experience-driven checklist together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9bfb954d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin Coroutines: Deep-Dive Interview Questions for Senior Engineers]]></title>
            <link>https://medium.com/@sandeep.jan19/mastering-kotlin-coroutines-deep-dive-interview-questions-for-senior-engineers-41557dcca5ec?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/41557dcca5ec</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[lead-developers]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 09:09:28 GMT</pubDate>
            <atom:updated>2025-12-26T09:09:28.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9YJ1RCVsoqNmdXG971rhA.png" /></figure><p>##<strong> TL;DR</strong><br>- `suspend` does NOT mean async or background<br>- Coroutines work as compiler-generated state machines<br>- Cancellation is cooperative, not forced<br>- `SupervisorJob` and `supervisorScope` solve different problems<br>- Most coroutine bugs come from ignored cancellation or blocking code<br>- The final section covers how to test coroutines correctly</p><p>This article is a continuation of <a href="https://medium.com/@sandeep.jan19/android-interview-deep-dive-part-1-kotlin-immutability-thread-safety-for-senior-developers-47a3c977db5b"><strong>Android Interview Deep Dive (Part 1): Kotlin, Immutability &amp; Thread-Safety for Senior Developers</strong>.</a></p><p>Before jumping into the interview questions, I recommend revisiting the coroutine fundamentals covered in my <a href="https://github.com/sandeepsankla/android-interview-deep-dive/tree/main/app/src/main/java/com/example/androidinterviewdeepdive/coroutine">GitHub</a> notes.</p><h3>##1. What does the suspend keyword actually mean?</h3><p>The suspend keyword does <strong>not</strong> mean background execution or async execution.</p><p>In simple terms:</p><blockquote><em>A </em><em>suspend function is allowed to </em><strong><em>pause its execution without blocking the thread</em></strong><em> and </em><strong><em>resume later from the same point</em></strong><em>.</em></blockquote><p>Important clarifications:</p><ul><li>suspend does <strong>not</strong> create a new thread</li><li>suspend does <strong>not</strong> automatically run on a background thread</li><li>It only enables <strong>non-blocking pause and resume</strong></li></ul><p><strong>When a suspend function pauses, the thread is released and reused.</strong></p><p>Most developers know how to use coroutines. <strong>Interviews test whether you understand why they behave the way they do.</strong></p><h3>##2. How Do Kotlin Coroutines Work Internally?(Suspend Functions → State Machine Explained)</h3><p>Kotlin Coroutines work by <strong>transforming every </strong><strong>suspend function into a state machine at compile time</strong>. Let’s break this down step by step.</p><h4>Why does Kotlin need a state machine?</h4><p><strong>A normal function:</strong><br>- Executes top to bottom<br>- Uses the call stack<br>- Once it returns, the stack is gone forever</p><p><strong>A suspend function, however:</strong><br>- Can pause in the middle<br>- Must release the thread<br>- Must later resume exactly from where it stopped</p><p>👉 A traditional call stack <strong>cannot support this behavior</strong>.</p><p>So Kotlin <strong>does not try to save the stack</strong>. Instead, the compiler converts every suspend function into a <strong>state machine</strong>.</p><h4>Simple suspend function example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf6d5bc3d4dfdf507c78aea2f469dce/href">https://medium.com/media/3bf6d5bc3d4dfdf507c78aea2f469dce/href</a></iframe><p>This function has <strong>two suspension points</strong>:</p><p>apiCall1()</p><p>apiCall2(token)</p><p>Each suspension point becomes a <strong>state</strong> in the generated state machine</p><p>The compiler transforms the function into something like this:</p><pre>class LoadUserContinuation(<br>    val completion: Continuation&lt;User&gt;<br>) : Continuation&lt;Any?&gt; {<br><br>    var label: Int = 0<br>    var result: Any? = null   // holds last suspend result<br>    var token: String? = null // survives suspension<br><br>    override fun resumeWith(result: Result&lt;Any?&gt;) {<br>        this.result = result.getOrNull()<br>        loadUser(this)<br>    }<br>}</pre><p>And internally, it generates:</p><ul><li>A <strong>Continuation object</strong></li><li>A <strong>state variable</strong> (commonly called label-&gt; 0, 1, 2)</li><li>Fields to store local variables,<br> token → stored (needed across suspend)<br> user → NOT stored<br> result → generic holder for resumed value</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd4db147ed18e138b7786d78b4553c25/href">https://medium.com/media/fd4db147ed18e138b7786d78b4553c25/href</a></iframe><h3>What happens at runtime (step by step)</h3><h3>Step 1: Start execution</h3><ul><li>label = 0</li><li>apiCall1() is invoked</li></ul><p>If apiCall1():</p><ul><li>Completes immediately → continue</li><li>Needs async work → returns COROUTINE_SUSPENDED</li></ul><h3>Step 2: Suspension happens</h3><p>When this line executes:</p><pre>return COROUTINE_SUSPENDED</pre><p>This means:</p><ul><li>Stop execution now</li><li>Save state in Continuation</li><li>Release the thread</li><li>Do NOT block anything</li></ul><p>The coroutine is now <strong>paused</strong>.</p><h3>Step 3: Resume happens</h3><p>When async work finishes:</p><pre>continuation.resume(value)</pre><p>happens internally:</p><ul><li>The same function is called again</li><li>label is now 1</li><li>Execution jumps directly to state 1</li></ul><p>No stack is restored.<br> No thread is tied.</p><h3>Step 4: Final completion</h3><ul><li>All states finish</li><li>Final result is returned</li><li>Coroutine completes</li></ul><h4>Why COROUTINE_SUSPENDED is required</h4><p>COROUTINE_SUSPENDED is a <strong>signal</strong>, not a value.</p><p>It tells the coroutine runtime:</p><blockquote><em>“This function is not done yet. Please pause execution.”</em></blockquote><p>Why this design matters:</p><ul><li>No thread blocking</li><li>Infinite scalability</li><li>Millions of coroutines possible</li></ul><h3>Why coroutines don’t save the call stack</h3><p>Saving the call stack would mean:</p><ul><li>Huge memory usage</li><li>Poor scalability</li><li>Thread-like behavior</li></ul><p>Instead, Kotlin:</p><ul><li>Saves only <strong>minimal state</strong></li><li>Keeps memory usage low</li><li>Makes coroutines lightweight</li></ul><h3>##3. Difference between launch and async?</h3><h3>launch</h3><ul><li>Fire-and-forget</li><li>Returns Job</li><li>Exceptions propagate immediately</li><li>Used for side effects</li></ul><h3>async</h3><ul><li>Used when a result is needed</li><li>Returns Deferred&lt;T&gt;</li><li>Exception is thrown on await()</li></ul><h3>Common mistake</h3><pre>async { apiCall() } // await() never called</pre><p>⚠️ <strong>Real Production Bug</strong><br> Using async without await() hides failures.<br> The coroutine may fail silently, and the crash appears much later or never.</p><h3><strong>##4. What does “cancellation is cooperative” mean?</strong></h3><h4>Cancellation Is a Request, Not a Command</h4><p>In Kotlin Coroutines, <strong>cancellation is cooperative</strong>.<br> This means you cannot forcibly “kill” a coroutine from the outside. When you cancel a Job or a CoroutineScope, you are only sending a <strong>request</strong> for the coroutine to stop. It is the coroutine’s responsibility to notice that request and terminate gracefully.</p><p>This design is intentional and is one of the key differences between coroutines and threads.</p><h4>How Cancellation Works in Practice</h4><p>A coroutine cooperates with cancellation in two main ways:</p><h4>1️⃣ Automatic Cooperation (Suspending Functions)</h4><p>Most standard suspending functions — such as <strong>delay(), </strong><strong>withContext()</strong>, and <strong>await()</strong>—are <strong>cancellation-aware</strong>.<br> Before or during execution, they check whether the coroutine has been cancelled. If so, they immediately throw a CancellationException and stop further execution.</p><h4>2️⃣ Manual Cooperation (CPU-bound Work)</h4><p>Problems arise when a coroutine performs long-running <strong>CPU-bound work</strong> without calling any suspending functions — for example, a tight while loop or a large computation.</p><p>In such cases, the coroutine:</p><ul><li>Never checks the cancellation signal</li><li>Ignores the cancel request</li><li>Continues running even after the scope is cancelled</li></ul><p>To make such code cancellable, <strong>you must check explicitly</strong>.</p><h4>The Developer’s Responsibility</h4><p>As a developer, it is your responsibility to ensure long-running coroutines are cooperative. Kotlin provides a few tools for this:</p><ul><li><strong>isActive</strong><br> A boolean flag that can be checked inside loops to stop execution when cancellation is requested.</li><li><strong>ensureActive()</strong><br> A convenience function that throws CancellationException immediately if the coroutine is no longer active.</li><li><strong>yield()</strong><br> Temporarily pauses the coroutine, checks for cancellation, and gives other coroutines a chance to run—useful for fairness in CPU-heavy work.</li></ul><p>A coroutine that ignores cancellation becomes a <em>zombie task</em>: still alive, still consuming CPU, and invisible to the UI lifecycle.</p><pre>//This coroutine will continue running even after the ViewModel is destroyed.<br><br>viewModelScope.launch {<br>    while (true) {<br>        heavyWork() // This ignores cancellation<br>    }<br>}<br><br></pre><blockquote><strong><em>The Golden Rule</em></strong><em><br></em>“Calling cancel() does not stop code. It only changes Job state. The coroutine decides when to stop.”</blockquote><h3>5. Does a coroutine always run on the same thread?</h3><p>No.</p><p><strong>A coroutine can:</strong><br>- Suspend on one thread<br>- Resume on anotherThe <strong>dispatcher</strong> decides thread usage, not the coroutine.</p><h3>##6. If coroutines are lightweight, how can bad coroutine code still crash an app?</h3><p>Because of:</p><ul><li>Blocking operations</li><li>Ignored cancellation</li><li>Swallowed CancellationException</li><li>Unstructured scopes (GlobalScope)</li><li>Dispatcher starvation</li></ul><h3>##7. Difference between SupervisorJob and supervisorScope?</h3><p>This is one of the most common “gotcha” questions in senior Android interviews. While both are used to isolate failures so that one crashing child doesn’t kill the whole neighborhood, they are used in different places and behave differently regarding <strong>Structured Concurrency</strong>.</p><h4>1. SupervisorJob (The “Scope Level” Tool)</h4><p>A SupervisorJob is a type of Job that you typically use when creating a long-lived CoroutineScope.</p><ul><li><strong>Behavior:</strong> If a child coroutine fails, the SupervisorJob does not stop. It allows other children to keep running.</li><li><strong>Where to find it:</strong> This is what viewModelScope uses under the hood. It ensures that if one network call in your ViewModel fails, the entire ViewModel (and other active tasks) doesn&#39;t shut down.</li></ul><h4>2. supervisorScope (The “Function Level” Tool)</h4><p>supervisorScope is a <strong>suspending function</strong>.1 It creates a sub-scope within an existing coroutine where failure is isolated.</p><ul><li><strong>Behavior:</strong> It waits for all children to complete (like coroutineScope), but if one child fails, it doesn&#39;t cancel the others or the parent.</li><li><strong>Usage:</strong> Use this when you have a specific block of code where you want to run multiple tasks in parallel, and you don’t want the whole block to fail just because one task did.</li></ul><p><strong>In an interview, a lead dev might ask: <em>“What happens if I do</em></strong><em> </em><em>launch(SupervisorJob()) { ... }?&quot;</em></p><p>The Answer: This is usually a mistake.</p><p>When you pass a new <strong>SupervisorJob()</strong> as a parameter to launch, you are making that coroutine a root job.</p><p><strong>Why this is dangerous:</strong><br>- The coroutine becomes a root job<br>- Parent cancellation won’t stop it<br>- Memory leaks become likely</p><blockquote><strong><em>Rule of Thumb:</em></strong><em> Use </em><em>SupervisorJob only when creating a new </em><em>CoroutineScope. Use </em><em>supervisorScope when you want to handle failures locally inside a function.</em></blockquote><h3>Example: Using supervisorScope</h3><p>Kotlin</p><pre>suspend fun loadDashboard() = supervisorScope {<br>    val user = launch { fetchUser() }      // If this fails...<br>    val news = launch { fetchNews() }      // ...this still continues.<br>    val weather = launch { fetchWeather() } <br>}</pre><p><strong>Rule of Thumb</strong><br><strong>- Creating a scope? → Use `SupervisorJob`<br>- Inside a function? → Use `supervisorScope</strong>`</p><h3>8. How do you Unit Test Kotlin Coroutines in Android?</h3><p>Testing coroutines is not just about calling runBlocking. For production-grade apps, you need to control <strong>Time</strong> and <strong>Execution</strong>.</p><h4>1. Handling Dispatchers.Main</h4><p>In Unit Tests, Dispatchers.Main uses the Android Looper.getMainLooper(), which is not available. To fix this, we use the kotlinx-coroutines-test library to replace the Main dispatcher.</p><p><strong>Pro-Tip:</strong> Use a <strong>JUnit Rule</strong> to automatically set and reset the Main dispatcher for every test.</p><p>Kotlin</p><pre><br>class MainDispatcherRule(<br>    val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()<br>) : TestWatcher() {<br>    override fun starting(description: Description) {<br>        Dispatchers.setMain(testDispatcher)<br>    }<br>    override fun finished(description: Description) {<br>        Dispatchers.resetMain()<br>    }<br>}</pre><h4>2. Using runTest instead of runBlocking</h4><p>runTest is the standard for testing. Its biggest advantage is <strong>Virtual Time skipping</strong>. If your code has a delay(10000), runTest will skip the wait and execute the test instantly.</p><h4>3. Standard vs. Unconfined Test Dispatcher</h4><ul><li><strong>StandardTestDispatcher:</strong> It doesn&#39;t execute tasks immediately. You have to manually call advanceTimeBy(ms) or runCurrent(). Use this when you want to test the <strong>sequence</strong> of events (e.g., checking if a Loading state is shown before the Data state).</li><li><strong>UnconfinedTestDispatcher:</strong> It starts the coroutine immediately. This is great for simple tests where you just want to verify the final result.</li></ul><h4>4. Testing Complex Flows (StateFlow/SharedFlow)</h4><p>When testing StateFlow, we often use .first() or .take(n).toList() to capture the emitted states.</p><ul><li><strong>Lead-Level Tip:</strong> For SharedFlow, always launch the collection in a background job within runTest because SharedFlow never completes on its own.</li></ul><p><strong>Why this matters for a Lead Dev:</strong></p><p>Testing proves that your <strong>Structured Concurrency</strong> is working. If your test hangs or leaks, it means your production code might have zombie coroutines.</p><p><strong>If you understand coroutine state machines and cooperative cancellation, most “tricky” coroutine interview questions stop being tricky. They become predictable</strong>.</p><p>Hello readers, what is the hardest coroutine bug you’ve ever debugged? Please do comment, it would help us to avoid such issues. If you found this useful, feel free to leave a clap or share your experience in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41557dcca5ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Android Interview Deep Dive (Part 1): Kotlin, Immutability & Thread-Safety for Senior Developers]]></title>
            <link>https://medium.com/@sandeep.jan19/android-interview-deep-dive-part-1-kotlin-immutability-thread-safety-for-senior-developers-47a3c977db5b?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a3c977db5b</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 20:31:36 GMT</pubDate>
            <atom:updated>2025-12-10T20:31:36.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKSCtPqeNMAvvPAsBTopTQ.png" /></figure><p>This article is <strong>Part 1 of my Android Interview Deep Dive series </strong>— helping senior devs master <strong>Kotlin, Coroutines, Compose, and Clean Architecture.</strong></p><blockquote><em>You don’t fail an interview because you don’t know — you fail because you didn’t </em><strong><em>explain deeply enough</em></strong><em> what you already know.”</em><br> — A lesson I learned the hard way.</blockquote><p>If you’re preparing for a <strong>Senior Android Developer</strong> interview (product company), this series is for you.</p><p>We’ll go <strong>topic by topic</strong>, not just with answers — but with real, low-level reasoning and code.<br> Each article will focus on one core area of Android expertise that interviewers often dig deep into.</p><p>Let’s begin with the <strong>foundation of all Android code</strong> — <strong>Kotlin immutability, val vs var, and thread safety</strong>.</p><h3>🧩 1. val vs var — The Real Difference (Not Just Syntax)</h3><p>Everyone knows:</p><pre>val name = &quot;Sandeep&quot;<br>var age = 25</pre><p>…but very few can <strong>explain deeply</strong> what really happens underneath.</p><h3>👉 val locks the reference, not the object</h3><p>When you write:</p><pre>val list = mutableListOf(1, 2, 3)<br>list.add(4)      // ✅ allowed<br>list = listOf(5) // ❌ compile error</pre><ul><li>val means you <strong>can’t reassign</strong> the variable list to point to a new object.</li><li>But the <strong>object itself</strong> (the list) is still <strong>mutable</strong>.<br> In memory, the reference stays the same — the data changes.</li></ul><p>So, if someone says “val makes it immutable&quot; — it’s <strong>half true</strong> at best.</p><h3>🧠 2. Copy-On-Write: Why Kotlin Doesn’t Do It for You</h3><p>In Kotlin standard library, <strong>no collection is copy-on-write(COW) </strong>by default.</p><pre>val a = mutableListOf(1, 2)<br>val b = a<br>b.add(3)<br>println(a)  // [1, 2, 3]</pre><p>Both a and b point to the <strong>same list object</strong>.<br> If you modify one, you modify both.</p><p>If you need immutability, use <strong>functional updates</strong>:</p><pre>val old = listOf(1, 2, 3)<br>val new = old + 4   // new list; old one untouched</pre><p>This is how functional architectures (and Jetpack Compose) achieve <strong>predictable state</strong> — <br> <em>no hidden side effects, no surprise mutations.</em></p><h3>⚙️ 3. val ≠ Thread-Safety (Here’s Why)</h3><p>Declaring a variable as val doesn’t magically make it safe for concurrency.</p><p>Thread-safety depends on:</p><ol><li><strong>Atomicity</strong> — can other threads interrupt the operation?</li><li><strong>Visibility</strong> — will other threads see the latest value?</li><li><strong>Ordering</strong> — are the reads/writes happening in a predictable sequence?</li></ol><p>Example:</p><pre>class Counter {<br>    var x = 0<br>    fun inc() { x++ }  // ❌ not atomic<br>}</pre><p>Multiple threads incrementing x can easily corrupt its value because:</p><ul><li>x++ is actually three operations: read → add → write.</li><li>Without synchronization, these operations can interleave.</li></ul><h3>⚡ 4. @Volatile — What It Does (and Doesn’t Do)</h3><p>@Volatile only ensures <strong>visibility</strong>, not atomicity.</p><pre>class Flag {<br>    @Volatile var running = true<br>}</pre><p>If one thread writes running = false, other threads will see it immediately.<br> But if you write:</p><pre>class Counter {<br>    @Volatile var x = 0<br>    fun inc() { x++ }<br>}</pre><p>It’s <strong>still not thread-safe</strong>. The increment is not atomic — two threads can read the same x, increment, and write back the same value.</p><p>✅ Use AtomicInteger or @Synchronized instead:</p><pre>val count = AtomicInteger(0)<br>fun inc() = count.incrementAndGet()</pre><p>or</p><pre>@Synchronized<br>fun inc() { x++ }</pre><h3>🧵 5. How to Actually Make It Thread-Safe</h3><p>There are <strong>three common strategies</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVsjC0yXbd3Otup2gTWCQQ.png" /></figure><h3>🪄 6. Compose + State = The Hidden Mutation Trap</h3><p>One of the most frequent bugs in Compose:</p><pre>@Composable<br>fun Tags() {<br>    val tags = mutableListOf(&quot;A&quot;, &quot;B&quot;)<br>    Button(onClick = { tags.add(&quot;C&quot;) }) { Text(&quot;Add&quot;) }<br>    LazyColumn { items(tags) { Text(it) } }<br>}</pre><p>The UI doesn’t update! Why?</p><p>Because tags is just a local mutable list —<br> its <strong>reference never changes</strong>, so Compose doesn’t recompose.</p><p>✅ The right way:</p><pre>@Composable<br>fun Tags() {<br>    var tags by remember { mutableStateOf(listOf(&quot;A&quot;, &quot;B&quot;)) }<br>    Button(onClick = { tags = tags + &quot;C&quot; }) { Text(&quot;Add&quot;) }<br>    LazyColumn { items(tags) { Text(it) } }<br>}</pre><p>Immutable + copy-on-write updates trigger recomposition properly.</p><h3>🧩 7. Quick Self-Check Exercises (for You to Try)</h3><p>Test your understanding before you scroll down 👇</p><ol><li>Why does this print [1, 2, 3, 99] twice?</li></ol><pre>val a = mutableListOf(1, 2, 3)<br>val b = a<br>b.add(99)<br>println(a)<br>println(b)</pre><p>2. Why can’t this compile?</p><pre>val box = Box(1)<br><br>box = Box(2)</pre><p>3. Fix this so the loop stops:</p><pre>var running = true<br>Thread {<br>    while (running) {}<br>}.start()<br>Thread.sleep(100)<br>running = false</pre><p>4. Fix this to make it atomic:</p><pre>class Counter {<br>    @Volatile var x = 0<br>    fun inc() { x++ }<br>}class Counter {     @Volatile var x = 0     fun inc() { x++ } }</pre><p>5. Why doesn’t this Compose code update the list?</p><pre>@Composable<br>fun Tags() {<br>    var tags by remember { mutableStateOf(listOf(&quot;A&quot;, &quot;B&quot;)) }<br>    Button(onClick = { tags = tags + &quot;C&quot; }) { Text(&quot;Add&quot;) }<br>    LazyColumn { items(tags) { Text(it) } }<br>}</pre><h3>✅ 8. Summary — Key Takeaways</h3><pre>| <strong>Concept</strong>              | <strong>What You Should Remember  </strong>                   |<br>| -------------------- | -------------------------------------------- |<br>| `<strong>val</strong>`                | Locks the reference, not the object          |<br>| <strong>Copy-on-write  </strong>      | You must do it manually in Kotlin            |<br>| <strong>Thread-safety </strong>       | Needs atomicity + visibility + ordering      |<br>| <strong>`@Volatile`</strong>          | Visibility only — no atomic guarantee        |<br>| <strong>Compose State</strong>        | Immutable updates trigger recomposition      |<br>|<strong> Shared mutable state</strong> | Avoid; use flows, channels, or state-holders |</pre><h3>🚀 Coming Next in the Series</h3><p>In the next parts of this <strong>Android Interview Deep Dive</strong> series, we’ll cover:</p><ul><li><strong>Part 2:</strong> Mastering Coroutines &amp; Flows — structured concurrency like a pro</li><li><strong>Part 3:</strong> Jetpack Compose internals &amp; performance traps</li><li><strong>Part 4:</strong> Clean Architecture, Dependency Inversion &amp; DI (Hilt)</li><li><strong>Part 5:</strong> Offline-first apps — Room, WorkManager, and sync reliability</li></ul><p>Follow me on Medium to get notified when the next part drops 👇<br> And if this helped you prep better, give it a 💚 clap — it helps more devs find this series!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a3c977db5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic Network layer in Flutter with Dio]]></title>
            <link>https://medium.com/@sandeep.jan19/generic-network-layer-in-flutter-with-dio-fe2202d9643d?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe2202d9643d</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-network]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-dio]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Mon, 30 May 2022 05:46:34 GMT</pubDate>
            <atom:updated>2022-05-30T05:46:34.004Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to create a generic network layer i.e REST API calls and parse JSON data using flutter network package -Dio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyOEGKSSwlefqf2JfxjYFA.png" /></figure><p>After comparing the several networking packages (<a href="https://pub.dev/packages/http">HTTP</a>, <a href="https://pub.dev/packages/dio">Dio</a>, <a href="https://pub.dev/packages/chopper">Chopper</a>, <a href="https://pub.dev/packages/retrofit">Retrofit</a>) of flutter, Finally, I decided to move with Dio.</p><p><strong>why </strong><a href="https://pub.dev/packages/dio"><strong>Dio</strong></a><strong>?</strong></p><p>Dio provides more features than other packages, with ease of implementation. Dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout, etc.</p><p><strong>How to call API with Dio</strong></p><p>Below is the sample code to call the different types (GET, PUT, POST, etc) of APIs calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05aa162cae423d74697365c96993502/href">https://medium.com/media/e05aa162cae423d74697365c96993502/href</a></iframe><p>This code is perfectly fine in fetching data and parsing the response, etc. But are you feeling the same which I am thinking of? Aww !! the problem with this code is how to make it more generic.</p><p>The issue with the above solution is :</p><p>❌ Generic way to call API.</p><p>❌ Duplicate Code becomes more and more on adding more services.</p><p>❌ Improper error handling.</p><p>Let’s think about how to make the network layer more generic, scalable, and proficient. Let’s start with the generic NetworkResponce class.</p><p>I am making a class with @<a href="https://pub.dev/packages/freezed">freezed</a> annotation. Freezed is a code-generation package that helps you to create data classes in Dart. It prevents you from writing hundreds of error-prone lines. This NetworkResponce class maintains the states of API call - success, loading, error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39697e09b8ffdaebe10709180094fd4c/href">https://medium.com/media/39697e09b8ffdaebe10709180094fd4c/href</a></iframe><p>Now let’s create a generic network service class. This class must have a method that accepts all the API requests and returns a response with proper handling. Below is the code for the Network service class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd7073c70ea59535d28872ed8107c50/href">https://medium.com/media/2cd7073c70ea59535d28872ed8107c50/href</a></iframe><p>Hurray!! we have resolved all the problems the only remaining part is how to use this network service class in our controller/ repository. So below is the sample for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95a220503b3983587f0ea61c87a226d/href">https://medium.com/media/f95a220503b3983587f0ea61c87a226d/href</a></iframe><p><strong>Summary</strong></p><p>We have achieved how to call a rest API in a highly optimized way and build a highly proficient and generic network layer with proper error handling. I will share a sample code with State management in a flutter with clean code soon in the next article. Lastly, I would like to request you to please share your views regarding this article and help me improve this more and more. And if you liked this article then please clap on this and share it with your network.</p><p>That’s it, hope it will help.!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe2202d9643d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline Android App with Cloud Firestore]]></title>
            <link>https://medium.com/@sandeep.jan19/offline-android-app-with-cloud-firestore-b6686e0520fb?source=rss-dbe1a4ef468------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6686e0520fb</guid>
            <category><![CDATA[android-app-developers]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[firestore]]></category>
            <dc:creator><![CDATA[Sandeep Sankla]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 06:08:23 GMT</pubDate>
            <atom:updated>2021-08-19T06:08:23.611Z</atom:updated>
            <content:encoded><![CDATA[<p>This quickstart shows you how to store data remotely, easily access them and monitor the changes in Real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI73sl1npMZXJiQv-ICHNQ.jpeg" /></figure><h4><strong>Cloud Firestore</strong></h4><p>Cloud Firestore is a cloud-hosted, NoSQL database that your application (Android, iOS, and web apps) can access directly via native SDKs. Like the Firebase Real-time Database, it keeps syncing our data via real-time listeners to the client app. It provides offline support for mobile and web so we can create responsive apps that work regardless of network latency or Internet connectivity.</p><p>Oh, I got it. You are thinking How it differs from Firebase&#39;s real-time Database. So here is the <a href="https://firebase.google.com/docs/firestore/rtdb-vs-firestore">answer</a> to your question. I hope, now you get more clarity of Firebase Vs Firestore after reading the answer.</p><p>Here is the <a href="https://firebase.google.com/docs/firestore/quickstart">link</a> to how to set up an Android project with cloud Firestore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*i7lvZX-lW1-v9KHi2QC4Ag.jpeg" /></figure><p>In this post, you will learn how to send data from the app to the cloud, how to access that data &amp; real-time data changes with<strong> Kotlin +MVVM pattern.</strong></p><p>Hope you all set up the app Gradle for cloud firestore, Now let&#39;s start our interesting journey. To make an offline app you follow three steps</p><ol><li>Decide the data Schema</li><li>Update/Push the data on firestore cloud</li><li>Add listener in the app to monitor the real-time data changes</li></ol><p>Let&#39;s discuss each point in detail:</p><ol><li><strong>Schema</strong> — In my sample app I have taken a sample schema of a Person, Very basic details of the person like -id, name, and city you can add as many you need, here is the sample data</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9db4ba42dd37153cd73f8b68b142e8a/href">https://medium.com/media/b9db4ba42dd37153cd73f8b68b142e8a/href</a></iframe><p><strong>2. Pushing Data on Cloud -</strong> To add document on Cloud you just need the collection reference of firestore and set the data, here is the sample code for that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c2f3a9640a071a49eb10513e0e980ae/href">https://medium.com/media/3c2f3a9640a071a49eb10513e0e980ae/href</a></iframe><p>3. <strong>Listener</strong> — You can <em>listen</em> to a document with the onSnapshot() method. The listener will help you observe the real-time changes in the document and helps to perform the necessary action. Here in our application, I am using addSnapshotListener with the callback — DocumentChange.Type.<em>ADDED, </em>DocumentChange.Type.<em>REMOVED, </em>DocumentChange.Type.<em>MODIFIED, So on each document(Person), added we are simply emitting the data &amp; populating it in the list. for more details about the listener —</em><a href="https://firebase.google.com/docs/firestore/query-data/listen"><em> read this</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8427ef7fb55974c65eb2c4d2f83cf3d/href">https://medium.com/media/d8427ef7fb55974c65eb2c4d2f83cf3d/href</a></iframe><p>Hope you enjoy this article, you can find the<a href="https://github.com/sandeepsankla/offline-App-with-Firestore"> project here</a>, Attaching a video for reference that will show you about document changes. You can make a chat -messaging app using firestore cloud as well. It’s my first article please mention it in the comment if you need more details of this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F589024950%3Fapp_id%3D122963%26h%3D0975c688f5&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F589024950&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1218344131_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e50bd51fe992dce507d102ab5f508c4/href">https://medium.com/media/7e50bd51fe992dce507d102ab5f508c4/href</a></iframe><p>Summary: In this article, you have learnt to use Firestore cloud real-time DB with android architecture(MVVM) pattern.</p><p>Clap is highly recommended for motivation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6686e0520fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>