<?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 Murtaza Khursheed on Medium]]></title>
        <description><![CDATA[Stories by Murtaza Khursheed on Medium]]></description>
        <link>https://medium.com/@aumaidkh?source=rss-69e8c0c4dc1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k7smDGz0G3fY0JputyO13w.jpeg</url>
            <title>Stories by Murtaza Khursheed on Medium</title>
            <link>https://medium.com/@aumaidkh?source=rss-69e8c0c4dc1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:55:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aumaidkh/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[Stop Lying to Yourself: Why “I’ll Fix It Later” is a Myth (And How to Kill It)]]></title>
            <link>https://medium.com/@aumaidkh/stop-lying-to-yourself-why-ill-fix-it-later-is-a-myth-and-how-to-kill-it-12ab20f84475?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ab20f84475</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 12:31:03 GMT</pubDate>
            <atom:updated>2026-01-14T12:31:03.243Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tB1EL5HCV_O3V6kpEMe6ag.png" /><figcaption>Image generated by Gemini nano banana Ai</figcaption></figure><p>Has this ever happened to you, It’s 11 PM in the night. The feature needs to ship tomorrow, so you compromise. You start writing the code, and it immediately begins to sprawl. The logic nests, the function hits 50 lines, and the indentation is not right. You know it’s ugly, but it works.</p><p>You tell yourself the lie we all believe: “I’ll refactor this next week.” You drop a // TODO comment and push the commit.</p><p>But that “next week” never comes. The TODO is ignored, the code rots, and that file becomes a danger zone nobody wants to touch. We don’t need more discipline to fix this; we need a system that stops believing our lies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xfs5lglGW8D2JuXQDw_lnw.png" /><figcaption>Image generated by Gemini nano banana Ai</figcaption></figure><h4>The Radical Solution: Weaponized Gradle</h4><p>What if we stopped relying on willpower and started relying on the compiler?</p><p>Imagine a build system which refuses to compile “dirty” code unless you explicitly sign a waiver. This isn’t just about linting; it’s about weaponizing your build tool to enforce the 20-Line Rule.</p><p>Uncle Bob said functions should be small. Really small. We use 20 lines as a red flag. That number? We made it up. Yet somehow, it fits. Once a function stretches past it, chances are high it’s juggling tasks. Pile on responsibilities, then one stumble crashes everything — testing becomes messy fast.</p><p>By implementing a strict Gradle task, we change the psychology of development. You can no longer “accidentally” leave a mess because you’re tired. If the build fails, you have to look the code in the eye. If you still want to merge it, you have to actively suppress the error in the config, leaving a permanent paper trail of your decision.</p><h4>The Implementation</h4><p>We aren’t going to use a heavy linter configuration that takes hours to tweak. We are going to write a ruthless, lightweight Gradle task using Kotlin DSL.</p><p>Place this logic in your buildSrc folder (or your convention plugins). This script acts as the enforcer. It scans your Kotlin files, ignores declarative code like UI or Themes (which are naturally verbose), and counts braces to find logic that has grown too large.</p><p>Here is the engine:</p><pre>package rules<br><br>import extensions.TechDebtExtension<br><br>// 1. Clean Code Standards<br>val MAX_FUNCTION_LINES = 20<br>val ARG_COUNT_WARNING_THRESHOLD = 3 // Triadic (Warn)<br>val ARG_COUNT_ERROR_THRESHOLD = 4   // Polyadic (Fail)<br><br>val techDebt = project.extensions.findByType&lt;TechDebtExtension&gt;()<br>    ?: project.extensions.create&lt;TechDebtExtension&gt;(&quot;techDebt&quot;)<br><br>val enforceFunctionRules by tasks.registering {<br>    group = &quot;verification&quot;<br>    description = &quot;Enforces Clean Code: Small functions (&lt; $MAX_FUNCTION_LINES lines) and limited arguments.&quot;<br><br>    val sourceFiles = fileTree(&quot;src&quot;) {<br>        include(&quot;**/*.kt&quot;)<br>        exclude(&quot;**/ui/theme/**&quot;)<br>        exclude(&quot;**/build/**&quot;)<br>        exclude(&quot;**/*Test.kt&quot;)<br>    }<br><br>    doLast {<br>        val lengthErrors = mutableListOf&lt;String&gt;()<br>        val argErrors = mutableListOf&lt;String&gt;()<br>        val argWarnings = mutableListOf&lt;String&gt;()<br><br>        sourceFiles.forEach { file -&gt;<br>            val lines = file.readLines()<br>            var currentFunctionName = &quot;&quot;<br>            var currentFunctionStartLine = 0<br>            var braceCount = 0<br>            var isInsideFunction = false<br>            var meaningfulLinesCount = 0<br><br>            // Signature Capture Variables<br>            var isCollectingSignature = false<br>            var signatureAccumulator = StringBuilder()<br><br>            lines.forEachIndexed { index, rawLine -&gt;<br>                val line = rawLine.trim()<br><br>                // Skip comments/imports<br>                if (line.startsWith(&quot;//&quot;) || line.startsWith(&quot;import &quot;) || line.startsWith(&quot;package &quot;)) return@forEachIndexed<br><br>                // --- 1. Detect Function Start ---<br>                val isFunctionDefinition = line.matches(Regex(&quot;^(.*\\s)?fun\\s+.*&quot;))<br><br>                if (isFunctionDefinition &amp;&amp; !isInsideFunction) {<br>                    isInsideFunction = true<br>                    isCollectingSignature = true<br>                    currentFunctionStartLine = index + 1<br><br>                    // Extract name safely considering modifiers<br>                    currentFunctionName = line.substringAfter(&quot;fun &quot;).substringBefore(&quot;(&quot;)<br><br>                    braceCount = 0<br>                    meaningfulLinesCount = 0<br>                    signatureAccumulator.clear()<br>                }<br><br>                // --- 2. Collect Signature for Arg Counting ---<br>                if (isCollectingSignature) {<br>                    signatureAccumulator.append(&quot; &quot;).append(line)<br>                    // Stop collecting when we hit the body start (&#39;{&#39;) or expression body (&#39;=&#39;)<br>                    if (line.contains(&quot;{&quot;) || line.contains(&quot;=&quot;)) {<br>                        isCollectingSignature = false<br><br>                        val argsCount = countArguments(signatureAccumulator.toString())<br><br>                        if (argsCount &gt;= ARG_COUNT_ERROR_THRESHOLD) {<br>                            argErrors.add(<br>                                &quot;   • [Too Many Arguments] ($argsCount args)\n&quot; +<br>                                        &quot;     Name:      $currentFunctionName\n&quot; +<br>                                        &quot;     Location:  (${file.name}:$currentFunctionStartLine)&quot;<br>                            )<br>                        } else if (argsCount == ARG_COUNT_WARNING_THRESHOLD) {<br>                            argWarnings.add(<br>                                &quot;   • [Triadic Function] ($argsCount args)\n&quot; +<br>                                        &quot;     Name:      $currentFunctionName\n&quot; +<br>                                        &quot;     Location:  (${file.name}:$currentFunctionStartLine)&quot;<br>                            )<br>                        }<br>                    }<br>                }<br><br>                // --- 3. Track Function Body Length ---<br>                if (isInsideFunction) {<br>                    braceCount += line.count { it == &#39;{&#39; }<br>                    braceCount -= line.count { it == &#39;}&#39; }<br><br>                    if (line.isNotEmpty()) {<br>                        meaningfulLinesCount++<br>                    }<br><br>                    // End of function<br>                    if (braceCount == 0 &amp;&amp; (line.contains(&quot;}&quot;) || line.endsWith(&quot;=&quot;))) {<br>                        if (meaningfulLinesCount &gt; MAX_FUNCTION_LINES) {<br>                            lengthErrors.add(<br>                                &quot;   • [Complex Function] ($meaningfulLinesCount lines)\n&quot; +<br>                                        &quot;     Name:      $currentFunctionName\n&quot; +<br>                                        &quot;     Location:  (${file.name}:$currentFunctionStartLine)&quot;<br>                            )<br>                        }<br>                        isInsideFunction = false<br>                    }<br>                }<br>            }<br>        }<br><br>        // --- 4. Reporting ---<br><br>        // Print Warnings (Does not fail build)<br>        if (argWarnings.isNotEmpty()) {<br>            println(&quot;\n⚠️  CLEAN CODE WARNINGS (Triadic Functions Detected):&quot;)<br>            argWarnings.forEach { println(it) }<br>            println(&quot;Consider refactoring these to use a data class or helper object.\n&quot;)<br>        }<br><br>        // Collect Failures<br>        val allFailures = lengthErrors + argErrors<br><br>        if (allFailures.isNotEmpty()) {<br>            val report = StringBuilder().apply {<br>                append(&quot;\n&quot;)<br>                append(&quot;╔════════════════════════════════════════════════════════════════════╗\n&quot;)<br>                append(&quot;║             🚫 CLEAN CODE VIOLATIONS DETECTED 🚫                   ║\n&quot;)<br>                append(&quot;╠════════════════════════════════════════════════════════════════════╣\n&quot;)<br>                append(&quot;║ MODULE:  ${project.name}\n&quot;)<br>                append(&quot;║\n&quot;)<br>                append(&quot;║ RULE 1:  Functions must be &lt; $MAX_FUNCTION_LINES lines.\n&quot;)<br>                append(&quot;║ RULE 2:  Arguments: 0-2 (Good), 3 (Warn), 4+ (Fail).\n&quot;)<br>                append(&quot;║\n&quot;)<br>                append(&quot;║ \&quot;The ideal number of arguments for a function is zero (niladic).\n&quot;)<br>                append(&quot;║  Next comes one (monadic), followed closely by two (dyadic).\n&quot;)<br>                append(&quot;║  Three arguments (triadic) should be avoided where possible.\n&quot;)<br>                append(&quot;║  More than three (polyadic) requires special justification\n&quot;)<br>                append(&quot;║  and shouldn&#39;t be used anyway.\&quot; -- Robert C. Martin\n&quot;)<br>                append(&quot;╚════════════════════════════════════════════════════════════════════╝\n&quot;)<br>                append(&quot;\n👇 ERRORS FOUND (${allFailures.size}):\n&quot;)<br>                append(&quot;──────────────────────────────────────────────────────────────────────\n&quot;)<br>                allFailures.forEach { append(it + &quot;\n──────────────────────────────────────────────────────────────────────\n&quot;) }<br>                append(&quot;\n❌ Build failed. Please refactor.\n&quot;)<br>            }<br>            throw GradleException(report.toString())<br>        }<br>    }<br>}<br><br>// Helper to parse argument count safely (handles generics &lt;T, U&gt; and parentheses nesting)<br>fun countArguments(signature: String): Int {<br>    val start = signature.indexOf(&#39;(&#39;)<br>    if (start == -1) return 0<br><br>    // Find the matching closing parenthesis<br>    var depth = 0<br>    var end = -1<br>    for (i in start until signature.length) {<br>        if (signature[i] == &#39;(&#39;) depth++<br>        if (signature[i] == &#39;)&#39;) depth--<br>        if (depth == 0) {<br>            end = i<br>            break<br>        }<br>    }<br><br>    if (end &lt;= start + 1) return 0 // Empty parens &quot;()&quot;<br><br>    val argsContent = signature.substring(start + 1, end)<br><br>    // Count commas at the &quot;top level&quot; (ignoring commas inside &lt;...&gt; or (...))<br>    var commaCount = 0<br>    var genericDepth = 0<br>    var parenDepth = 0<br><br>    for (char in argsContent) {<br>        when (char) {<br>            &#39;&lt;&#39; -&gt; genericDepth++<br>            &#39;&gt;&#39; -&gt; if (genericDepth &gt; 0) genericDepth--<br>            &#39;(&#39; -&gt; parenDepth++<br>            &#39;)&#39; -&gt; if (parenDepth &gt; 0) parenDepth--<br>            &#39;,&#39; -&gt; {<br>                if (genericDepth == 0 &amp;&amp; parenDepth == 0) {<br>                    commaCount++<br>                }<br>            }<br>        }<br>    }<br><br>    return commaCount + 1<br>}<br><br>tasks.configureEach {<br>    val taskName = name.lowercase()<br>    val shouldSkip = techDebt.flags.get().contains(&quot;skipFunctionLengthCheck&quot;)<br><br>    if (!shouldSkip) {<br>        if ((taskName.contains(&quot;compile&quot;) &amp;&amp; taskName.contains(&quot;kotlin&quot;)) || taskName == &quot;prebuild&quot;) {<br>            dependsOn(enforceFunctionRules)<br>        }<br>    }<br>}</pre><p>The error message isn’t a standard stack trace; it’s a statement. When this hits your console, it demands attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lW6htzKAeWemgYFkF-mmeA.png" /></figure><h4>The Escape Hatch: Intentional Technical Debt</h4><p>This is where most of the strict linting rules die. In tight deadlines, you may need to ship dirty code to ship faster If the build breaks at 11:30 PM and you can’t bypass it, you won’t fix the code — you’ll just delete the rule entirely.</p><p>We don’t want to delete the rule. We want to bypass it explicitly.</p><p>The solution is the TechDebtExtension. It changes “accidental rot” (forgetting to clean up) into “managed debt” (signing a waiver).</p><p>The Usage<br>Here is how you configure the “Emergency Hatch” in your module’s build.gradle.kts.</p><pre>// 1. Apply the extension (assuming you registered it in your plugin)<br>val techDebt = project.extensions.create&lt;TechDebtExtension&gt;(&quot;techDebt&quot;)<br><br>// 2. The &quot;Break Glass&quot; Configuration<br>techDebt {<br>    // Uncomment this line ONLY when urgency demands dirty code.<br>    // Remove it immediately after the deadline.<br>    <br>    // include(&quot;skipFunctionLengthCheck&quot;) <br>}<br><br>// 3. Bind the logic to your build<br>tasks.register&lt;EnforceFunctionLength&gt;(&quot;enforceFunctionLength&quot;)<br><br>tasks.configureEach {<br>    val flags = techDebt.flags.get()<br>    val shouldSkip = flags.contains(&quot;skipFunctionLengthCheck&quot;)<br>    <br>    // Hook into the compilation process<br>    if (!shouldSkip &amp;&amp; (name == &quot;preBuild&quot; || name.contains(&quot;compileDebugKotlin&quot;))) {<br>         dependsOn(&quot;enforceFunctionLength&quot;)<br>    }<br>}</pre><p>When you are crunching for a deadline, you uncomment include(&quot;skipFunctionLengthCheck&quot;). The build passes. You ship the feature.</p><p>But — and this is the key — you have left a paper trail. You haven’t just ignored a warning; you have explicitly modified the build configuration to say, “I am consciously bypassing safety protocols.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVrjSbzgCVeLYZi3jPPPSA.png" /></figure><h4>The Payoff: Paying the Debt</h4><p>The deadline passes. The feature is live, and the panic subsides. You finally have some breathing room.</p><p>In a normal project, this is where you’d forget about the mess you made. But not here.</p><p>You open build.gradle.kts and find the waiver you signed: include(&quot;skipFunctionLengthCheck&quot;)</p><p>You delete it.</p><p>Immediately, your build breaks. The console lights up, pointing a finger directly at the 50-line logic monster you wrote last week. It doesn’t nag you with a warning; it <strong>blocks</strong> you. You cannot compile until you settle the account.</p><p>This is the payoff. You are forced to look at the code. You extract the validation logic into a private helper function. You move the data mapping to its own class. You turn one long, confusing block into three short, readable ones.</p><p>You run the build again. It passes.</p><p>You didn’t just write code; you managed a financial transaction with your codebase. You borrowed time, and now you’ve paid it back with interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tMKNZ24vQebFdGEN9dbjw.png" /><figcaption>Image generated by Gemini nano banana Ai</figcaption></figure><p>Conclusion</p><p>Discipline is hard to maintain. But automation is easy.</p><p>If you rely on your memory to go back and fix “TODO” comments you had added, you will most likely fail. The “urgent” will always displace the “important.”</p><p>By setting the rules into the build system, you enforce it to let you still write bad code if you absolutely need to meeting those tight deadlines, but you can no longer do it by accident and forget to fix it later.</p><p>Your Next Steps:</p><p>Copy the script from Section 3 into your project.</p><p>Run it and watch it fail.</p><p>See the debt. You might be surprised by how much “Cognitive Overload” is currently hiding in your source folder.</p><p>But don’t panic. Don’t try to fix it all at once. Add the techDebt exclusion and then start paying off the loan one file at a time.</p><p>And finally stop lying to yourself about “next week” instead let the compiler tell you the truth.</p><h4><strong>Resources &amp; Code</strong></h4><p>You can find the full, copy-pasteable <em>enforce-function-length-check.gradle.kts.kt </em>script in the GitHub repository below:</p><p>👉 [GitHub] (<a href="https://github.com/the-mobile-architect/GradleRulesExample">GradleRulesExample</a>)</p><p><strong>Share Your Thoughts</strong><br>Is 20 lines too ruthless? Or is it exactly the kind of discipline we need to stop the rot?</p><p>I’d love to hear how your team handles the “I’ll fix it later” trap. Do you have a “Bank of Technical Debt,” or do you just hope for the best?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ab20f84475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ TOAD: A Kotlin-First Architecture Pattern That Finally Made My ViewModels Boring]]></title>
            <link>https://medium.com/@aumaidkh/toad-a-kotlin-first-architecture-pattern-that-finally-made-my-viewmodels-boring-b615a9ab6c30?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b615a9ab6c30</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 16:57:03 GMT</pubDate>
            <atom:updated>2026-01-04T16:16:19.174Z</atom:updated>
            <content:encoded><![CDATA[<p>How I accidentally created an architecture pattern while trying to stop my ViewModels from becoming monsters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORzMfKnCttCcjeA1eANOlg.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>I have a confession to make.</p><p>Last year, I opened a ViewModel file in our codebase that had grown to 847 lines. Eight. Hundred. Forty. Seven. Lines of business logic, state management, API calls, and enough `<em>viewModelScope.launch</em>` blocks to make my IDE&#39;s scroll bar look like a thin sliver of despair.</p><p>We&#39;ve all been there. You start with a clean, simple ViewModel. Then product asks for &quot;just one more feature.&quot; Then another. Then another. Before you know it, you&#39;re staring at a class that does everything from fetching user data to calculating the meaning of life.</p><p>I knew there had to be a better way. After months of experimentation, countless refactors, and more than a few late nights, I landed on something that changed how I think about ViewModels entirely.</p><p>I call it <strong>TOAD</strong> , Typed Object Action Dispatch.</p><h4>The Problem Nobody Wants to Talk About</h4><p>Let&#39;s be honest about what happens in most Android/KMP projects.</p><p>You start here:</p><pre>class ProfileViewModel : ViewModel() {<br>  fun loadProfile() { /* clean, simple */ }<br>}</pre><p>And six months later, you&#39;re here:</p><pre>class ProfileViewModel : ViewModel() {<br>  fun loadProfile() { /* ... */ }<br>  fun updateName() { /* ... */ }<br>  fun updateEmail() { /* ... */ }<br>  fun uploadPhoto() { /* ... */ }<br>  fun deleteAccount() { /* ... */ }<br>  fun changePassword() { /* ... */ }<br>  fun connectSocialMedia() { /* ... */ }<br>  fun verifyPhone() { /* ... */ }<br>  fun updateNotificationSettings() { /* ... */ }<br>  fun exportData() { /* ... */ }<br>  fun toggleDarkMode() { /* ... */ }<br>// ... 30 more methods<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lUyhogt4ih1VW8qTri6iA.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>Every time you need to add a feature, you crack open the ViewModel and add another method. The class grows. Tests become harder. Code reviews become longer. And that one developer who wrote half the methods? They left six months ago.</p><p>This isn&#39;t just messy code. This is a violation of one of the most fundamental principles in software design: the <strong>Open/Closed Principle</strong>.</p><blockquote>&quot;Software entities should be open for extension, but closed for modification.&quot;</blockquote><p>Every feature request means <strong><em>modifying</em></strong> the ViewModel. We&#39;re doing it backwards.</p><h4>What if ViewModels Never Had to Change?</h4><p>This question haunted me. What would it look like if, once written, a ViewModel never needed modification?</p><p>The answer came from an unexpected place: the Command Pattern.</p><p>What if, instead of methods on a ViewModel, we had <strong>objects that represent actions</strong>? Self-contained, testable, swappable objects that encapsulate exactly one piece of business logic?</p><pre>// Instead of this:<br>viewModel.loadProfile()<br>// What about this:<br>viewModel.runAction(LoadProfile)</pre><p>This tiny shift in thinking changed everything.</p><h4>Introducing TOAD 🐸</h4><p><strong>TOAD</strong> stands for:</p><ul><li><strong>T</strong>yped — Compile-time type safety ensures actions can only work with compatible state and events</li><li><strong>O</strong>bject — Actions are first-class objects, not methods buried in a class</li><li><strong>A</strong>ction — Each action encapsulates exactly one responsibility</li><li><strong>D</strong>ispatch — A single entry point for all state changes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMHF0BqcbyWhrUlozpSeBw.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>Here&#39;s the core idea: Your ViewModel has <strong>one public function</strong>. That&#39;s it. One.</p><pre>class ProfileViewModel(...) : ToadViewModel&lt;ProfileState, ProfileEvent&gt;(...) {<br>  fun runAction(action: ProfileAction) = dispatch(action)<br>}</pre><p>New feature? Don&#39;t touch the ViewModel. Create a new action:</p><pre>data object ShareProfile : ProfileAction() {<br>  override suspend fun execute(<br>    dependencies: ProfileDependencies,<br>    scope: ActionScope&lt;ProfileState, ProfileEvent&gt;<br>  ) {<br>      val shareUrl = dependencies.userRepo.getShareUrl()<br>      scope.sendEvent(ProfileEvent.ShareProfile(shareUrl))<br>    }<br>}</pre><p>That&#39;s it. The ViewModel remains untouched. Tests for existing features remain valid. The risk of breaking something? Virtually zero.</p><h4>The Anatomy of TOAD</h4><p>Let me walk you through how this actually works.</p><p>1. <strong>ViewState</strong> — Your Single Source of Truth</p><p>State is immutable. Always. Changes happen through `<em>copy()</em>`.</p><pre>data class ProfileState(<br>  val isLoading: Boolean = false,<br>  val user: User? = null,<br>  val error: String? = null<br>) : ViewState</pre><p>2. <strong>ViewEvent</strong> — One-Time Side Effects</p><p>Events are for things that shouldn&#39;t live in state: navigation, toasts, analytics.</p><pre>sealed interface ProfileEvent : ViewEvent {<br>  data class ShowToast(val message: String) : ProfileEvent<br>  data object NavigateToSettings : ProfileEvent<br>}</pre><p>3. <strong>ActionDependencies</strong> — Injected Once, Used Everywhere</p><p>Instead of passing repositories to each action, bundle them:</p><pre>class ProfileDependencies(<br>  override val coroutineScope: CoroutineScope,<br>  val userRepository: UserRepository,<br>  val analyticsTracker: AnalyticsTracker<br>) : ActionDependencies()</pre><p>4. <strong>ViewAction</strong> — The Heart of TOAD</p><p>This is where the magic happens. Each action is a typed object that knows exactly what state it operates on, what events it can emit, and what dependencies it needs:</p><pre>data object LoadProfile : ProfileAction() {<br>  override suspend fun execute(<br>    dependencies: ProfileDependencies,<br>    scope: ActionScope&lt;ProfileState, ProfileEvent&gt;<br>  ) {<br>      scope.setState { copy(isLoading = true) }<br>      val user = dependencies.userRepository.getCurrentUser()<br>      scope.setState { copy(isLoading = false, user = user) }<br>      dependencies.analyticsTracker.track(&quot;profile_loaded&quot;)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RU-1IpFbxdf5IK-WwPzAw.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>5. <strong>ActionScope</strong> — Controlled State Access</p><p>Actions don&#39;t get direct access to the StateFlow. They get a controlled `ActionScope` that provides safe, well-defined operations:</p><pre>class ActionScope&lt;S : ViewState, E : ViewEvent&gt; {<br>  val currentState: S<br>  fun setState(reducer: S.() -&gt; S)<br>  fun sendEvent(event: E)<br>  suspend fun withLoading(...)<br>}</pre><p><strong>6. ToadViewModel</strong> — The Orchestrator</p><p>The ViewModel&#39;s only job is to dispatch actions. It&#39;s boring. And boring is exactly what we want:</p><pre>abstract class ToadViewModel&lt;S : ViewState, E : ViewEvent&gt;(<br>initialState: S<br>) : ViewModel() {<br>  abstract val dependencies: ActionDependencies<br>  val state: StateFlow&lt;S&gt;<br>  val events: Flow&lt;E&gt;<br>  protected fun dispatch(action: ViewAction&lt;...&gt;)<br>}</pre><h4>Why This Changes Everything</h4><p><strong>1. True Open/Closed Compliance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLNOSTGMW9iXfEdSK87-gw.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>With TOAD, adding features means adding files, not modifying them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3f7BOxxFWoGjpxj0eCYQdg.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p><strong>2. Actions Are Stupidly Easy to Test</strong></p><p>Testing a traditional ViewModel means instantiating the whole thing with all its dependencies. Testing a TOAD action?</p><pre>@Test<br>fun `LoadProfile updates state with user data`() = runTest {<br>  val mockRepo = mockk&lt;UserRepository&gt;()<br>  val mockScope = mockk&lt;ActionScope&lt;ProfileState, ProfileEvent&gt;&gt;(relaxed = true)<br>  coEvery { mockRepo.getCurrentUser() } returns User(&quot;John&quot;)<br>  LoadProfile.execute(ProfileDependencies(TestScope(), mockRepo), mockScope)<br>  verify { mockScope.setState(match { it(ProfileState()).user?.name == &quot;John&quot; }) }<br>}</pre><p>No ViewModel instantiation. No complex setup. Just the action, its dependencies, and assertions.</p><p><strong>3. Type Safety You Can Feel</strong></p><p>The generic signature `<em>ViewAction&lt;D, S, E&gt;</em>` ensures you can&#39;t accidentally use a `ProfileAction` with a `SettingsViewModel`. The compiler catches it. Not your users.</p><p><strong>4. Perfect for Code Reviews</strong></p><p>When reviewing a PR that adds a feature, you&#39;re looking at:</p><ul><li>One new action file</li><li>Maybe a new event type</li><li>That&#39;s it</li></ul><p>No scrolling through a 500-line ViewModel diff trying to spot what changed.</p><h4>Real-World Usage</h4><p>Here&#39;s what using TOAD looks like in a Composable:</p><pre>@Composable<br>fun ProfileScreen(viewModel: ProfileViewModel = koinViewModel()) {<br>  val state by viewModel.state.collectAsStateWithLifecycle()<br>  LaunchedEffect(Unit) {<br>  viewModel.events.collect { event -&gt;<br>    when (event) {<br>      is ProfileEvent.ShowToast -&gt; showToast(event.message)<br>      is ProfileEvent.NavigateToSettings -&gt; navController.navigate(&quot;settings&quot;)<br>      }<br>    }<br>  }<br>  ProfileContent(<br>    state = state,<br>    onRefresh = { viewModel.runAction(RefreshProfile) },<br>    onEditClick = { viewModel.runAction(OpenEditDialog) },<br>    onPhotoClick = { viewModel.runAction(UploadPhoto(it)) }<br>  )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4hTXC1jnCZ39hlLnj0AxQ.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>Every user interaction maps to an action. Every action is explicit, traceable, and testable.</p><h4>The Unexpected Benefits</h4><p>After using TOAD in production for several months, some benefits surprised me:</p><p><strong>Onboarding is faster:</strong> New developers don&#39;t need to understand the entire ViewModel. They can look at one action, understand it completely, and contribute.</p><p><strong>Debugging is clearer:</strong> When something goes wrong, you know exactly which action caused it. There&#39;s no hunting through a monolithic class.</p><p><strong>Refactoring is safer:</strong> Moving an action to a different module? Just move the file. No surgery on the ViewModel.</p><p><strong>Code ownership is natural:</strong> Different team members can own different actions without stepping on each other.</p><h4>When NOT to Use TOAD</h4><p>I&#39;m not going to pretend this is perfect for every situation.</p><p>If your screen has one or two simple operations, TOAD might be overkill. A traditional ViewModel with two methods is fine. Really.</p><p>If your team is deeply invested in another architecture (MVI libraries like Orbit, MVI Kotlin, etc.), migrating might not be worth the effort.</p><p>But if you&#39;re starting fresh, or your ViewModels are getting out of control, give TOAD a try.</p><h4>Getting Started</h4><p>TOAD is just a pattern — there&#39;s no library to install. The core implementation is about 150 lines of Kotlin.</p><p>Here&#39;s the skeleton:</p><pre>// StateContracts.kt<br>interface ViewState<br><br>interface ViewEvent<br><br>abstract class ActionDependencies {<br>  abstract val coroutineScope: CoroutineScope<br>}<br>// ActionContracts.kt<br>interface ViewAction&lt;D : ActionDependencies, S : ViewState, E : ViewEvent&gt; {<br>    suspend fun execute(dependencies: D, scope: ActionScope&lt;S, E&gt;)<br>}<br><br>class ActionScope&lt;S : ViewState, E : ViewEvent&gt;(<br>    private val stateFlow: MutableStateFlow&lt;S&gt;,<br>    private val eventChannel: Channel&lt;E&gt;<br>) {<br>    val currentState: S get() = stateFlow.value<br>    fun setState(reducer: S.() -&gt; S) = stateFlow.update(reducer)<br>    fun sendEvent(event: E) = eventChannel.trySend(event)<br>}<br>// ToadViewModel.kt<br>abstract class ToadViewModel&lt;S : ViewState, E : ViewEvent&gt;(<br>initialState: S<br>) : ViewModel() {<br>    protected abstract val dependencies: ActionDependencies<br>    private val _state = MutableStateFlow(initialState)<br>    val state: StateFlow&lt;S&gt; = _state.asStateFlow()<br>    private val _events = Channel&lt;E&gt;(Channel.BUFFERED)<br>    val events: Flow&lt;E&gt; = _events.receiveAsFlow()<br>    protected fun &lt;D : ActionDependencies&gt; dispatch(action: ViewAction&lt;D, S, E&gt;) {<br>        viewModelScope.launch {<br>            action.execute(dependencies as D, ActionScope(_state, _events))<br>        }<br>    }<br>}</pre><p>That&#39;s the entire framework. Copy it, paste it, and start building.</p><h4>Final Thoughts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdwOp3n1Lnqsd0-qf8LZeg.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>I didn&#39;t set out to create an architecture pattern. I just wanted my ViewModels to stop growing into unmanageable beasts.</p><p>TOAD emerged from frustration, iteration, and a stubborn belief that there had to be a better way. It&#39;s not revolutionary — it&#39;s just the Command Pattern applied thoughtfully to modern Android/KMP development.</p><p>But sometimes the best solutions aren&#39;t revolutionary. They&#39;re just... right.</p><p>Your ViewModels should be boring. Your actions should be interesting.</p><p>Give TOAD a try. Your future self (and your code reviewers) will thank you.</p><p>Checkout the GitHub repository for examples;</p><p><a href="https://github.com/the-mobile-architect/TOAD-Example">https://github.com/the-mobile-architect/TOAD-Example</a></p><blockquote><em>If you found this useful, I&#39;d love to hear about your experience implementing TOAD in your projects. Drop a comment or reach out — let&#39;s make ViewModels boring together.</em>🐸</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b615a9ab6c30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eliminating Loading Indicators: The Architecture of Optimistic User Interfaces]]></title>
            <link>https://medium.com/@aumaidkh/eliminating-loading-indicators-the-architecture-of-optimistic-user-interfaces-bcbca58502a9?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcbca58502a9</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 05:22:24 GMT</pubDate>
            <atom:updated>2025-12-21T15:12:13.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Perceived Performance Through Latency Compensation</h3><p>Network latency remains a persistent challenge in mobile and web application development. Even with modern 5G infrastructure, server round-trip times frequently range between 200 and 500 milliseconds. Implementing blocking user interfaces that await server confirmation for every interaction can result in a sluggish user experience that highlights the underlying network constraints.</p><p>Leading applications, such as Instagram, Twitter, and Trello, circumvent this issue by avoiding loading indicators for standard interactions like “liking” or “archiving.” Instead, these platforms employ a strategy known as <strong>Optimistic UI</strong>.</p><p>Optimistic UI updates the interface state preemptively, displaying a success state before the server has confirmed the action. This article examines the architectural implementation of this pattern, with a specific focus on the critical necessity of error handling and state reconciliation.</p><h3>Comparative Analysis: Pessimistic versus Optimistic Request Lifecycles</h3><p>To understand the latency issues inherent in standard applications, one must examine the traditional request lifecycle, referred to as the “Pessimistic” approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61HanClbFCru_ur_JIaIww.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p><strong>The Pessimistic Lifecycle:</strong></p><ol><li>The user initiates an action (e.g., taps a button).</li><li>The client sends a request to the server.</li><li><strong>The client displays a loading indicator</strong>, blocking further interaction or visual feedback.</li><li>The server responds with a success status (e.g., “200 OK”).</li><li>The client updates the User Interface (UI).</li></ol><p>While this method ensures state consistency, it introduces significant friction, as every user interaction necessitates a waiting period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNoiIqW-OBMnx2lNHrxnGQ.png" /><figcaption>Optimistic Image created by Nano banana using Gemini AI</figcaption></figure><p><strong>The Optimistic Lifecycle:</strong> In contrast, Optimistic UI alters the order of operations to prioritize responsiveness:</p><ol><li>The user initiates an action.</li><li><strong>The client updates the UI immediately.</strong></li><li>The client sends the request to the server in the background.</li></ol><p>This approach operates on the statistical probability that the vast majority of requests will succeed. Psychologically, this eliminates perceived latency, making the application appear local and instantaneous. However, from an architectural perspective, assuming success introduces the risk of <strong>State Inconsistency</strong>.</p><p>If the UI reflects a successful operation but the server returns an error, the client has presented false information to the user. A robust design must address this discrepancy.</p><h3>Architectural Implementation: Decoupling Intent from Synchronization</h3><p>Production-level implementation of Optimistic UI requires decoupling the user’s intent from the network synchronization process. This is typically achieved through a three-step architectural flow:</p><h3>Step 1: The Local Mutation</h3><p>Upon user interaction, an event is dispatched to the State Manager (e.g., ViewModel, Bloc, or Redux Store). The local model is updated immediately (isLiked = true), and the UI observes this change to render the updated state. This process typically executes within a single frame (approximately 16 milliseconds).</p><h3>Step 2: The Shadow Request</h3><p>Following the local state update, the side-effect handler initiates the API call asynchronously. It is imperative that this request does not block the user interface. Furthermore, the request must be scoped correctly to survive context changes, such as the user navigating away from the current view or placing the application in the background.</p><h3>Step 3: State Reconciliation</h3><p>The server response triggers the reconciliation phase:</p><ul><li><strong>Success (200 OK):</strong> No further action is required as the UI already reflects the correct state.</li><li><strong>Failure (400/500/Timeout):</strong> The system must execute a <strong>Rollback</strong> operation.</li></ul><h3>Managing Failure Scenarios: The Rollback Mechanism</h3><p>A distinguishing feature of robust software architecture is the handling of the “unhappy path,” such as network failures or server errors. If a request fails, the UI creates a discrepancy between the visible state and the server’s source of truth.</p><p>To maintain integrity, a rigorous Rollback Mechanism is required.</p><pre>fun onLikeClicked() {<br>    // 1. State Preservation<br>    // Capture the state prior to modification to ensure a clean rollback.<br>    val previousState = state.value<br>    // 2. Optimistic Update<br>    // The UI updates instantly to reflect the anticipated success.<br>    updateState(isLiked = true)<br>    // 3. Asynchronous Network Request<br>    repository.likePost(postId).onError { error -&gt;<br>        <br>        // 4. THE ROLLBACK<br>        // Upon failure, the system must revert to the preserved state.<br>        updateState(previousState) <br>        <br>        // Optional: Provide user feedback regarding the failure.<br>        showToast(&quot;Action failed. Please check your connection.&quot;)<br>    }<br>}</pre><p>As demonstrated in step 1, preserving previousState is essential. In the event of an API error, the system must strictly emit the preserved state effectively undoing the optimistic update. While the visual reversion may be noticeable to the user, it is preferable to the alternative of a non-responsive interface.</p><h3>Operational Constraints and Edge Cases</h3><p>Optimistic UI is not a universal solution and should be applied selectively based on specific constraints.</p><h3>Constraint 1: High-Stakes Transactions</h3><p>Optimistic UI should generally be avoided for financial or critical data transactions. For example, a funds transfer should not be reported as complete until server confirmation is received. In these scenarios, the certainty provided by a loading indicator is preferable to the confusion caused by a rollback.</p><h3>Constraint 2: Dependent State Consistency</h3><p>When a user performs an action that affects other views (e.g., “liking” an item that should arguably appear in a “Favourites” list), race conditions may occur. If the user navigates to the secondary view before the server processes the initial request, data inconsistency may arise. To mitigate this, distinct views should observe a Single Source of Truth rather than relying on independent network fetches.</p><h3>Constraint 3: Rapid Successive Interactions (Race Conditions)</h3><p>If a user rapidly toggles a state (e.g., “Like” -&gt; “Unlike” -&gt; “Like”), multiple API calls may be generated. If these requests arrive at the server out of order, the final server state may differ from the client state. Implementing Request Debouncing or a Serial Operation Queue is necessary to ensure requests are processed in the correct order.</p><h3>Conclusion</h3><p>Optimistic UI serves as a powerful pattern for improving perceived performance and respecting the user’s time. However, it requires a disciplined approach that separates UI state from server state and implements rigorous reconciliation logic for failure scenarios.</p><p>By removing loading indicators for standard interactions and handling errors gracefully, developers can create applications that feel significantly more responsive and professional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcbca58502a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How writing SOLID code saved my AI Chatbot from a last-minute disaster.]]></title>
            <link>https://medium.com/@aumaidkh/how-writing-solid-code-saved-my-ai-chatbot-from-a-last-minute-disaster-7c4659b87d80?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c4659b87d80</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 14:17:49 GMT</pubDate>
            <atom:updated>2025-12-21T15:12:49.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6-Dzg3xg0HBgs9qnt3pZA.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><p>When you’re building complex features under tight deadlines, there’s one thing that always pays off — clean, modular design. Recently, I learned this the hard way (and thankfully, in time to save my project).</p><p>This post walks you through how <strong>a last-minute tech stack change</strong> almost broke weeks of work — and how <strong>adhering to SOLID principles</strong> turned what could’ve been a nightmare into a seamless fix.</p><h3>The Setup: Building an AI-Powered Chatbot</h3><p>I was tasked with building an <strong>AI-powered chatbot</strong> for a mobile app — a conversational assistant powered by Gemini.</p><p>The requirements weren’t trivial:</p><ul><li>Full <strong>error handling</strong> (graceful fallbacks when the network fails)</li><li>A <strong>retry mechanism</strong> (because flaky connectivity happens)</li><li><strong>Message persistence</strong> using Firestore, so chats are stored even after restarts</li><li>A <strong>clean UI</strong> with proper state management</li><li>Built-in <strong>kill switches</strong> to disable the chatbot feature if needed</li></ul><p>After weeks of work, I had a robust, tested implementation. Everything worked beautifully.</p><p>Until it didn’t.</p><h3>The Twist: “We’re Switching to Firebase AI”</h3><p>Just when I thought I could finally relax, I got the news:</p><blockquote><em>“We’re no longer using the HTTP-based Gemini client. We’re moving to Firebase AI.”</em></blockquote><p>My heart sank.</p><p>The Gemini client was deeply integrated into the app — from message streaming to response parsing. Swapping it out sounded like <strong>tearing down a house to rebuild the foundation</strong>.</p><p>At least, that’s what it should have been…<br> But thanks to SOLID principles, it wasn’t.</p><h3>The Saviour: SOLID Code Design</h3><p>From day one, I designed my chatbot module using <strong>SOLID principles</strong> — particularly <strong>Dependency Inversion</strong> and <strong>Interface Segregation</strong>.</p><p>Here’s what that looked like:</p><h3>1. Defining an Abstraction</h3><p>Instead of coupling the app directly to Gemini, I created a ChatBot interface that defined the contract for all chatbot operations:</p><pre>interface ChatBot {<br>    suspend fun sendMessage(message: String): ChatResponse<br>    fun retryLastMessage()<br>    fun clearConversation()<br>}</pre><p>This meant the rest of the app — UI, Firestore logic, retry system — never knew or cared <strong>which</strong> chatbot was behind the scenes.<br> It only interacted with the ChatBot abstraction.</p><h3>2. Implementing the Gemini Client</h3><p>Originally, I had a Gemini-based implementation:</p><pre>class GeminiChatBot(<br>    private val apiClient: GeminiApiClient<br>) : ChatBot {<br>    override suspend fun sendMessage(message: String): ChatResponse {<br>        return apiClient.sendMessage(message)<br>    }<br>    override fun retryLastMessage() {<br>        // Implementation for retry mechanism<br>    }<br>    override fun clearConversation() {<br>        // Clear persisted data if needed<br>    }<br>}</pre><p>This class handled everything Gemini-specific , HTTP calls, response parsing, and error handling.</p><h3>3. Injecting the Dependency</h3><p>In my ViewModel, I injected the ChatBot interface rather than a concrete implementation:</p><pre>@HiltViewModel<br>class ChatViewModel @Inject constructor(<br>    private val chatBot: ChatBot<br>) : ViewModel() {<br>    fun onMessageSend(text: String) {<br>        viewModelScope.launch {<br>            val response = chatBot.sendMessage(text)<br>            // Update UI state<br>        }<br>    }<br>}</pre><p>So far, nothing unusual, just clean architecture. But this separation was about to save me.</p><h3>The Change: Replacing Gemini with Firebase AI</h3><p>When the Firebase AI requirement dropped, I simply created a <strong>new class implementing the same interface</strong>:</p><pre>class FirebaseAiChatBot(<br>    private val firebaseAiClient: FirebaseAiClient<br>) : ChatBot {<br>      override suspend fun sendMessage(message: String): ChatResponse {<br>          return firebaseAiClient.getResponse(message)<br>      }<br>      override fun retryLastMessage() {<br>          // Firebase-specific retry logic<br>      }<br>      override fun clearConversation() {<br>          // Firebase-specific cleanup<br>      }<br>  }<br>}</pre><p>Then, in my <strong>Hilt module</strong>, I switched the binding:</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object ChatModule {<br>    @Provides<br>    fun provideChatBot(<br>        firebaseAiClient: FirebaseAiClient<br>    ): ChatBot = FirebaseAiChatBot(firebaseAiClient)<br>}</pre><p>That’s it.<br> <strong>No refactoring in the ViewModel.</strong><br> <strong>No broken tests.</strong><br> <strong>No late-night debugging.</strong></p><p>All because everything depended on an abstraction, not an implementation.</p><h3>The Takeaway: SOLID Isn’t Just Theory</h3><p>This experience reinforced one of my favourite lessons:</p><blockquote><em>Writing SOLID code doesn’t just make things “clean.”<br>It makes your system resilient to change, even drastic ones.</em></blockquote><p>When you:</p><ul><li>Depend on <strong>interfaces</strong>, not concrete classes</li><li>Keep your modules <strong>loosely coupled</strong></li><li>Design with <strong>replaceability</strong> in mind</li></ul><p>…you’re not just writing good code , you’re <strong>future-proofing</strong> your work.</p><h3>Key Lessons Learned</h3><ol><li><strong>Abstractions are your insurance policy, </strong>they protect you when requirements change.</li><li><strong>Dependency Injection</strong> makes switching implementations painless.</li><li><strong>Interface-first design</strong> gives you confidence to pivot fast.</li><li><strong>SOLID principles aren’t theoretical</strong> , they save projects in the real world.</li></ol><h3>Final Thoughts</h3><p>In the end, switching from Gemini to Firebase AI took me <strong>minutes, not weeks</strong>.<br>Not because I was lucky, but because I had built the system with <strong>flexibility by design</strong>.</p><p>So the next time you’re tempted to skip defining an interface or think “I’ll just inject it later,” remember:<br> Your future self might thank you when the next last-minute requirement lands in your inbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c4659b87d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured UI State Management in Presentation Layer]]></title>
            <link>https://medium.com/@aumaidkh/structured-ui-state-management-in-presentation-layer-49f6ad82554c?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f6ad82554c</guid>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 16:35:03 GMT</pubDate>
            <atom:updated>2025-12-21T15:13:15.944Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR</strong></p><p>This article introduces a clean and scalable approach to managing UI state and side effects in Android using Kotlin Coroutines and Flow. The UiStateManager class decouples state logic from ViewModels, enabling testable, reusable, and lifecycle-aware updates with support for one-time events like navigation or toasts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol2CGKQBDp0J4Mr-5NezNw.png" /><figcaption>Image created by Nano banana using Gemini AI</figcaption></figure><h4><strong>Introduction</strong></h4><p>Modern Android apps require robust, maintainable, and reactive UI state management. As applications grow, so does the complexity of handling user interactions, async operations, and UI updates. Traditional ViewModel implementations often become bloated with mixed concerns: handling actions, updating state, and emitting one-time effects (e.g., navigation).</p><p>To address this, we introduce a structured abstraction: UiStateManager. It encapsulates the mechanics of state mutation, action execution, and effect emission, leaving your ViewModel focused on lifecycle coordination and exposing flows to the UI.</p><h4>Problem</h4><p>Managing complex UIs in Android can lead to:</p><ul><li><strong><em>ViewModel bloat</em></strong> : Mixing business logic, input validation, and effect emissions.</li><li><strong><em>Uncontrolled state mutations</em></strong> : Hard-to-track changes across multiple methods.</li><li><strong><em>Side-effect spaghetti</em></strong> : Navigation, snackbars, or analytics triggered inconsistently.</li><li><strong><em>Poor testability</em></strong> : Logic tightly coupled to Android framework classes.</li></ul><p>Developers often struggle with keeping their UI layer clean while ensuring predictable, asynchronous, and lifecycle-safe updates.</p><h4>Solution Overview</h4><p>The UiStateManager pattern introduces a clear separation between:</p><ul><li>UI Layer (Activity/Fragment): Observes state and reacts to effects.</li><li>ViewModel : Coordinates lifecycle and delegates action/state management.</li><li>UiActionHandler : Encapsulates discrete UI-driven logic units.</li><li>ExecutionContext : Injects dependencies needed by actions.</li></ul><p>Here’s a simplified architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNbYt9052TZHNS4g74BpwQ.png" /><figcaption>High Level Architecture Diagram</figcaption></figure><h4>Implementation Details</h4><ul><li>Define your UI State and Effects</li></ul><pre>data class LoginUiState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val isLoading: Boolean = false<br>)<br><br>sealed interface LoginEffect {<br>    data class ShowError(val message: String) : LoginEffect<br>    object NavigateNext : LoginEffect<br>}</pre><ul><li>Create an Execution Context</li></ul><pre>class LoginContext(<br>    val authRepository: AuthRepository,<br>    val logger: Logger<br>) : ActionExecutionContext</pre><p>. Implement UiActionHandler</p><blockquote>Each user interaction is encapsulated as an action:</blockquote><pre>class UpdateEmailAction(private val newEmail: String) :<br>    UiActionHandler&lt;LoginUiState, LoginEffect, LoginContext&gt; {<br><br>    override suspend fun execute(<br>        state: MutableStateFlow&lt;LoginUiState&gt;,<br>        effectChannel: Channel&lt;LoginEffect&gt;,<br>        executionContext: LoginContext<br>    ) {<br>        state.value = state.value.copy(email = newEmail)<br>    }<br>}</pre><ul><li>Initialize <em>UiStateManager </em>in ViewModel</li></ul><pre>class LoginViewModel(userRepo: UserRepository) : UiStateManagerViewModel&lt;LoginUiState, LoginEffect, LoginContext&gt;() {<br><br>    override val uiStateManager = UiStateManager(<br>        initialState = LoginUiState(),<br>        scope = viewModelScope,<br>        context = LoginContext(userRepo),<br>        initialActions = listOf(LoadUserSessionAction())<br>    )<br>}</pre><ul><li>Trigger Actions from UI</li></ul><pre>fun onEmailChanged(newEmail: String) {<br>    onAction(UpdateEmailAction(newEmail))<br>}</pre><h4>Key Components Explained</h4><h4><strong>UiStateManager</strong></h4><p>Holds:</p><ul><li>_state: MutableStateFlow&lt;UiState&gt; for internal mutation.</li><li>_effect: Channel&lt;UiEffect&gt; for one-time event emissions.</li></ul><p>Provides:</p><ul><li>start(): Runs initial actions once.</li><li>submit(action): Processes a UiActionHandler.</li><li>updateState(transform): For simple synchronous updates.</li></ul><h4><strong>UiActionHandler</strong></h4><p>A functional interface that defines how each UI interaction affects the state or emits an effect.</p><ul><li>Pure function pattern ensures predictability.</li><li>Can be reused across screens if generic enough.</li></ul><h4>ActionExecutionContext</h4><p>Decouples dependency access from the ViewModel, improving testability and reusability.</p><ul><li>No need to inject repositories directly into actions.</li><li>Allows passing lambdas, services, or mockables.</li></ul><h4>Base ViewModel Class</h4><p>Abstracts common patterns:</p><ul><li>Exposes uiState and uiEffect flows.</li><li>Delegates action submission to UiStateManager.</li></ul><h4>Best Practices And Pitfalls</h4><p><strong>✅ Best Practices</strong></p><ul><li>Use sealed interfaces for effects : Ensures exhaustive handling in UI.</li><li>Keep execute() pure : Avoid side-effects outside effectChannel.</li><li>Group related actions : Use base abstract handlers per screen for DRY code.</li><li>Inject dependencies via context : Not singletons or ViewModel properties.</li><li>Use trySend() for non-blocking effect emission : Prevents coroutine hangs.</li></ul><p><strong>⚠️ Common Mistakes</strong></p><ul><li>❌ Mutating state directly outside UiActionHandler.</li><li>❌ Emitting effects without using channels (e.g., calling Toast.makeText() inside handler).</li><li>❌ Starting UiStateManager multiple times unintentionally.</li><li>❌ Overloading execute() with complex logic — split into use cases if needed.</li></ul><h4>Testability And Extensibility</h4><p>Because all logic lives in UiActionHandler, you can write unit tests without mocking Android components:</p><pre>@Test<br>fun `email update action should set email`() = runTest {<br>    val state = MutableStateFlow(LoginUiState())<br>    val effectChannel = Channel&lt;LoginEffect&gt;()<br>    val context = LoginContext(mockAuth, mockLogger)<br><br>    UpdateEmailAction(&quot;test@example.com&quot;).execute(state, effectChannel, context)<br><br>    assertEquals(&quot;test@example.com&quot;, state.value.email)<br>}</pre><p>Extending the system is straightforward:</p><ul><li>Add new UiActionHandlers.</li><li>Extend UiEffect sealed types.</li><li>Reuse UiStateManager logic across features.</li></ul><h4>Conclusion</h4><p>The UiStateManager offers a clean, modular, and testable solution for managing UI state and effects in Android. By isolating UI logic into discrete, composable actions, it promotes:</p><ul><li>Single Responsibility Principle compliance</li><li>Predictable state transitions</li><li>Lifecycle-safe coroutines</li><li>Easy testability</li></ul><p>This architecture fits well within MVVM or MVI-inspired designs and scales gracefully with app complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f6ad82554c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nail Runtime Permissions in Android in simple 3 steps! ]]></title>
            <link>https://medium.com/@aumaidkh/nail-runtime-permissions-in-android-in-simple-3-steps-ea58b12fafd6?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea58b12fafd6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 11:21:10 GMT</pubDate>
            <atom:updated>2023-11-19T11:23:02.454Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of Android development, runtime permissions play a vital role in granting apps access to sensitive data and device features while they are actively running. These permissions encompass various aspects such as camera usage, location tracking, or contact retrieval. Despite their significance for app functionality, dealing with these permissions can often be challenging during development.</p><p>Traditionally, requesting these permissions involved a convoluted process that required developers to write numerous lines of code and handle user dialogs meticulously while ensuring error-free execution. This cumbersome approach discouraged developers impeded the speedy creation of apps and caused frustration among users due to permission-related complications.</p><p>Fortunately, an innovative solution has emerged that simplifies this intricate procedure into a mere three steps. This revolutionary technique evolutionizes the entire permission request mechanism by streamlining it effectively. Consequently, it minimizes inconvenience for developers and empowers them to seamlessly integrate essential permissions without compromising on user experience or impairing app functionality.</p><h3>Streamlining Permissions with EasyPermissionHandler</h3><p>Enter EasyPermissionHandler, the game-changer in the realm of Android development. This powerhouse of a library redefines how we approach runtime permissions, making the once-daunting process a breeze.</p><p>By harnessing the capabilities of this library, developers can bid farewell to the labyrinth of code typically required for handling permissions in Android apps. With just a few lines, this library empowers you to navigate through the intricate permission request procedure swiftly and efficiently.</p><p>Moreover, EasyPermissionHandler takes charge of the user experience intricacies, intelligently deciding when to present the rationale behind permission requests and seamlessly redirecting users to the settings screen when necessary. Let’s delve into how incorporating this library transforms the ordeal of managing runtime permissions in Android, liberating developers from the complexity and unlocking a seamless, hassle-free approach in just three simple steps.</p><figure><img alt="Rationale Dialog Previews" src="https://cdn-images-1.medium.com/max/617/1*w8IDV3OVlvLjnexSc396zA.png" /></figure><h3>Effortless Implementation: &lt;5 Steps to Android Permissions Mastery</h3><ul><li>Add the below line to the <strong><em>settings.gradle</em></strong> file inside the root of your project.</li></ul><pre>dependencyResolutionManagement {<br>  repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)<br>  repositories {<br>   mavenCentral()<br>   maven { url &#39;https://jitpack.io&#39; } // Add this line<br>  }<br> }</pre><ul><li>Add the below line to the dependencies section of <strong><em>build.gradle</em></strong> ( <strong><em>Module level</em></strong> )</li></ul><pre>dependencies {<br>     // other dependencies ...<br>    // Add the below dependency<br>    implementation &#39;com.github.Aumaidkh:EasyPermissionHandler:$latest_version&#39;<br> }</pre><ul><li>Add the permission to the AndroidManifest.xml</li></ul><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>  xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br> &lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot;/&gt;<br> &lt;application<br>  ......<br>  ......<br>  &gt;<br> &lt;/application&gt;<br>&lt;/manifest&gt;</pre><h4>Step 1. Get hold of IPermissionHandler inside Activity/Fragment.</h4><p>The permission handler gives us access to the method <strong><em>requestPermissionsIfNeeded</em></strong> which we are going to call while requesting permissions.</p><pre>class MainActivity: AppCompatActivity(){<br>    // Get reference to permission Handler<br>    private val permissionHandler by getPermissionHandler()<br><br>}</pre><h4>Step 2. Create an instance of PermissionRationaleContentProvider.</h4><p>We are going to create our own instance for the permission by extending it from the <strong><em>PermissionRationaleContentProvider</em></strong> which also enforces us to override a method <strong><em>getPermissionRationaleContent</em></strong>. This method also has a parameter <strong><em>isPermissionDeclined</em></strong> and on the basis of this we can change the rationale text as you can see in the below example.</p><pre>class NotificationRationaleContentProvider: PermissionRationaleContentProvider{<br>        override fun getPermissionRationaleContent(isPermanentlyDeclined: Boolean): RationaleContent {<br>            return RationaleContent(<br>                title = &quot;Allow this app to send you Notifications&quot;,<br>                message = if (isPermanentlyDeclined) &quot;Seems like you have denied the Notification permissions permanently. Please grant the permission from the Settings&quot; else &quot;This app requires notification access to keep you updated.&quot;,<br>                positiveButtonText = if (isPermanentlyDeclined) &quot;Go to settings&quot; else &quot;Grant&quot;,<br>                negativeButtonText = if (isPermanentlyDeclined) &quot;No thanks&quot; else &quot;Deny&quot;<br>            )<br>        }<br>    }</pre><h4>Step 3. Requesting permissions actually.</h4><p>As mentioned in the first step we are going to make use of the method <strong><em>requestPermissionIfNeeded</em></strong> which accepts some parameters.</p><ul><li><em>permission</em>: The permission which is to be requested.</li><li><em>rationaleContent</em>: The rationale content provider which is going to provide the text to the rationales that are to be displayed.</li><li><em>versionCheckToEscape</em> ( Optional ): If there is some specific build version check onto which we don’t want to request the permissions.</li></ul><pre>class MainActivity : AppCompatActivity() {<br><br>    /**<br>     *Step 1:  Get an instance of the permission handler<br>     * */<br>    private val permissionHandler by getPermissionHandler()<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        // Step 3: Ask Permissions<br>        permissionHandler.requestPermissionIfNeeded(<br>            permission = Manifest.permission.POST_NOTIFICATIONS,<br>            rationaleContent = NotificationRationaleContentProvider()<br>        )<br><br>    }<br><br>    /**<br>     * Step 2: Create Rationale Content Provider*/<br>    class NotificationRationaleContentProvider: PermissionRationaleContentProvider{<br>        override fun getPermissionRationaleContent(isPermanentlyDeclined: Boolean): RationaleContent {<br>            return RationaleContent(<br>                title = &quot;Allow this app to send you Notifications&quot;,<br>                message = if (isPermanentlyDeclined) &quot;Seems like you have denied the Notification permissions permanently. Please grant the permission from the Settings&quot; else &quot;This app requires notification access to keep you updated.&quot;,<br>                positiveButtonText = if (isPermanentlyDeclined) &quot;Go to settings&quot; else &quot;Grant&quot;,<br>                negativeButtonText = if (isPermanentlyDeclined) &quot;No thanks&quot; else &quot;Deny&quot;<br>            )<br>        }<br>    }<br><br>}</pre><h3>Conclusion</h3><p>As we wrap up this journey through streamlined permission requests, remember this newfound simplicity. Gone are the days of intricate code blocks and tangled dialogs. Now, armed with <strong><em>EasyPermissionHandler</em></strong>, you possess a potent tool to swiftly integrate permissions while focusing on what truly matters — building exceptional apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea58b12fafd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revamp Your Android App with Smartlook: A Step-by-Step Guide to Integration.]]></title>
            <link>https://medium.com/@aumaidkh/revamp-your-android-app-with-smartlook-a-step-by-step-guide-to-integration-2a32ed1db283?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a32ed1db283</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[smartlook]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[crashlytics]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Thu, 04 May 2023 05:52:39 GMT</pubDate>
            <atom:updated>2023-05-04T05:52:39.101Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Introduction</em></strong>: <br>In today’s competitive market, it’s essential to provide the best user experience to stand out from the crowd. Integrating Smartlook into your Android app can help you achieve this by providing valuable insights into user behavior and optimizing the app accordingly. In this article, we will discuss why Smartlook is the best tool to integrate into an Android app and provide a step-by-step guide on how to do it.</p><p><strong><em>Why Smartlook</em></strong>: <br>Smartlook is a user behavior analytics tool that enables you to track user activity and identify patterns in real-time. With Smartlook, you can view session recordings, heatmaps, event tracking, and conversion funnels, which allows you to analyze how users interact with your app. It helps you make data-driven decisions and optimize your app to enhance the user experience.</p><h4>How to integrate into an Android Application</h4><p>Integrating Smartlook into your Android app is a straightforward process. Follow the steps below to get started:</p><p><em>Step 1:Create a Smartlook Account.</em><br>The first step is to create a Smartlook account. Go to the Smartlook website and sign up for a free account. Once you’ve created an account, log in to the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjxKPDio7llxy0J5PEzD_w.png" /></figure><p><em>Step 2: Create a New Project.</em><br>After logging in, you’ll see the Smartlook dashboard. Click on the “Create New Project” button and give your project a name and note down the API_KEY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDBRQj3tnOp5GPxK9qX6Fg.png" /></figure><p><em>Step 3: Add Smartlook to your Android App.</em><br>To add Smartlook to your Android app, you need to integrate the Smartlook SDK. You can do this by adding the following code to your app’s build.gradle file:</p><pre>repositories {<br>    mavenCentral()<br>}<br>dependencies {<br>    implementation &#39;com.smartlook.sdk:smartlook:17.0.0&#39;<br>}</pre><p><em>Step 4: Initialize Smartlook.</em><br>Next, you need to initialize Smartlook in your app’s code. Add the following code to your app’s application class:</p><pre>class MyCustomApplication : Application() {<br>  override fun onCreate() {<br>    super.onCreate()<br>        <br>    val smartlook = Smartlook.instance  <br>    smartlook.preferences.projectKey = &quot;YOUR PROJECT KEY&quot;<br>    smartlook.start()<br>  }<br>}</pre><p>Make sure to replace “YOUR_API_KEY” with your Smartlook project’s API key.</p><p><em>Step 5: Start Recording.</em><br>Once you’ve initialized Smartlook, it will automatically start recording user sessions. You can view these sessions in the Smartlook dashboard.</p><pre>class MyCustomApplication : Application() {<br>  override fun onCreate() {<br>    super.onCreate()<br>        <br>    val smartlook = Smartlook.instance  <br>    smartlook.preferences.projectKey = &quot;YOUR PROJECT KEY&quot;<br>    // Starting Recording...<br>    smartlook.start()<br>  }<br>}</pre><p><strong><em>Conclusion:<br></em></strong>Integrating Smartlook into your Android app is a simple process that can provide you with valuable insights into user behavior. By tracking user activity and identifying patterns, you can optimize your app to provide the best user experience. Follow the steps outlined in this article to integrate Smartlook into your Android app today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a32ed1db283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Zoho SDK into Android App]]></title>
            <link>https://medium.com/@aumaidkh/integrate-zoho-sdk-into-android-app-ef8807a7a877?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8807a7a877</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[zoho]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 07:48:48 GMT</pubDate>
            <atom:updated>2023-02-15T07:48:48.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zq5gfXbrNHf2dByk" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">Firmbee.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>By utilizing the ASAP SDK for Android, you can offer convenient assistance to users of your Android application. This SDK allows you to establish and personalize an add-on that is embedded within your application, providing users with effortless access to the following:</p><ul><li>Your customer support team (to create support tickets or communicate with support representatives)</li><li>Your knowledge base (to access help articles)</li><li>Your user community (to engage with other application users) This feature provides great value to users as they no longer need to leave the application or navigate to your website or send an email to reach out for assistance. By accessing help from within the app, users can save time and enjoy an enhanced customer experience.</li></ul><p><strong>Setting up the SDK in ZOHO</strong></p><p>To add the ASAP add-on to your Android application, you must first create and register the add-on in Zoho Desk. To create the add-on, follow the steps outlined below:</p><ol><li>Navigate to the ASAP section in Zoho Desk by selecting Setup from the top menu, then choosing Channels, and finally selecting ASAP.</li><li>In the Setup pane located on the left-hand side, click on the + button beside Mobile under ASAP. This action will take you to the Create Mobile Add-On page.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGBdu5YYA-ckOnLu0pTvEg.png" /></figure><p>3. Under <strong>Add-On Details</strong>, configure the following settings:</p><ul><li><strong><em>Name</em></strong>: Give a name for the ASAP add-on (this is only for reference purposes and won’t appear on the app UI).</li><li><strong><em>Available</em></strong><em> </em>For: Choose which departments the ASAP add-on will be enabled for.</li><li><strong><em>Bundle ID:</em></strong> Enter the Bundle ID (<em>applicationId</em>) of your Android app. This information can be found in your app’s build.gradle file. This is mandatory to enable Live Chat and push notifications.</li><li><strong><em>Live Chat</em></strong>: Use the toggle switch to enable or disable Live Chat. The chat channel settings must be configured in your help desk portal.</li><li><strong><em>Push Notifications</em></strong>: Use the toggle switch to enable or disable push notifications. If you want to enable push notifications, you must enter the GCM/FCM server key in the “Enter GCM/FCM key” field. You can retrieve this key from the Firebase Console. JWT-based user authentication is required to enable notifications, and push notifications related to tickets are not sent to anonymous users.</li><li><strong><em>Authentication</em></strong>: Choose between Anonymous (for guest users who can submit tickets, view user community posts, and chat with a support agent) or JWT (for authenticated users who can do all that guest users can do, as well as view and track the status of their tickets, reply/comment on tickets, and participate in the user community with additional actions).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKfVElTqgpib48EE2ZDMBQ.png" /></figure><h4>Integrating the SDK into your App</h4><p>To integrate the SDK into your android app follow below steps:</p><ol><li>Add the following snippet to the <em>project </em>level <em>build.gradle</em>.</li></ol><pre>allrepositories { <br>    ......<br>    jcenter()<br>    maven { url &#39;https://maven.google.com/&#39; }<br>    maven { url &#39;http://maven.zohodl.com/&#39; }<br>}</pre><p>2. Add the following snippet to the <em>module</em> level <em>build.gradle</em> file.</p><pre>dependencies { compile &#39;com.zoho.desk:asapsdk:&lt;latest_version&gt;&#39; }</pre><p>There you go you’ve set up the SDK into your Android App.</p><h4>Progaurd Setup</h4><p>If minify and <em>progaurd </em>are enabled, the following rules need to be added to the <em>progaurd-rules</em> set.</p><pre>-keep class com.zoho.** {*;} -keep interface android.support.v7.** { *; } -keep class android.support.v7.** { *; } -keep interface android.support.v4.** { *; } -keep class android.support.v4.** { *; } -keepattributes Signature -keepattributes Annotation -keep class okhttp3.* { *; } -keep interface okhttp3.* { *; } -dontwarn okhttp3.** -dontwarn okio.** -dontwarn com.zoho.accounts.** -dontwarn com.squareup.okhttp.** -dontwarn okio.** -dontwarn retrofit2.**</pre><h4>Initialize the SDK into your App</h4><p>For initializing the SDK into your app the following fields are needed.</p><ul><li><strong>Org ID</strong></li><li><strong>App ID</strong></li><li><strong>Datacenter</strong></li></ul><p>The values of these keys appear under the <strong>Code Snippet</strong> section in the setup page of the ASAP add-on, in Zoho Desk.</p><p>To initialize the SDK in your app, add the following code snippet to a subclass of the Application class.<br>This is how the application class looks like</p><pre>import android.app.Application;<br>import com.zoho.deskportalsdk.DeskConfig;<br>import com.zoho.deskportalsdk.ZohoDeskPortalSDK;<br>public class MyApplication extends Application {<br><br>    public static ZohoDeskPortalSDK deskInstance;<br><br>    @Override public void onCreate() { <br>          super.onCreate();<br>          ZohoDeskPortalSDK.Logger.enableLogs();<br>          DeskConfig config = new DeskConfig.Builder().build();<br>          deskInstance = ZohoDeskPortalSDK.getInstance(this);<br>          // Paste your OrgId, AppId and DataCenter<br>          deskInstance.initDesk(orgId, appId, dataCenterValue, config);<br>   } <br><br>}</pre><h4>Displaying Help Components</h4><p>This is pretty much it. Now you are good to go for displaying the <em>ZOHO </em>components.</p><ul><li><a href="https://help.zoho.com/portal/en/kb/desk/for-developers/asap/android-sdk/articles/working-with-asap-sdk-for-android-version-1-0-and-2-0#Displaying_Help_Components"><em>SDK Dashboard</em></a></li></ul><pre>.....<br><br>public class MainActivity extends AppCompatActivity {<br><br>    @Override<br>    public void onCreate(){<br>      super.onCreate();<br>    <br>      // Displaying the Dashboard<br>      MyApplication.deskInstance.showHome(this);<br>    }<br><br>}</pre><ul><li><a href="https://help.zoho.com/portal/en/kb/desk/for-developers/asap/android-sdk/articles/working-with-asap-sdk-for-android-version-1-0-and-2-0#Knowledge_Base"><em>Knowledge Base</em></a></li></ul><pre>public class MainActivity extends AppCompatActivity {<br><br>    @Override<br>    public void onCreate(){<br>      super.onCreate();<br>    <br>      // Displaying the Dashboard<br>      MyApplication.deskInstance.showKB(this);<br>    }<br><br>}</pre><ul><li><a href="https://help.zoho.com/portal/en/kb/desk/for-developers/asap/android-sdk/articles/working-with-asap-sdk-for-android-version-1-0-and-2-0#Tickets"><em>Submit Ticket</em></a></li></ul><pre>public class MainActivity extends AppCompatActivity {<br><br>    @Override<br>    public void onCreate(){<br>      super.onCreate();<br>    <br>      // Displaying the Dashboard<br>      MyApplication.deskInstance.submitTicket(this);<br>    }<br><br>}</pre><h4>Conclusion</h4><p>In conclusion, integrating the ASAP SDK add-on into your Android app can greatly improve the customer support experience for your end-users. With the ability to quickly access your support team, knowledge base, and user community without having to leave your app, users can save time and receive a more seamless support experience. By following the steps outlined for configuring the add-on in Zoho Desk, you can easily customize and enable the features that work best for your app and its users, creating a more personalized and effective support experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8807a7a877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Take a Screenshot of Activity which has a SupportMapFragment nested inside it Android.]]></title>
            <link>https://medium.com/@aumaidkh/how-to-take-a-screenshot-of-activity-which-has-a-supportmapfragment-nested-inside-it-android-1a2d1284f48a?source=rss-69e8c0c4dc1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2d1284f48a</guid>
            <category><![CDATA[google-map-api]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Murtaza Khursheed]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 09:08:19 GMT</pubDate>
            <atom:updated>2023-01-31T09:41:10.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Take a Screenshot of Activity which has a SupportMapFragment nested inside it.</h3><p>Android provides a lot of useful APIs and components to build mobile applications. One of these components is the <em>SupportMapFragment</em>, which is used to show maps in an Android app. But sometimes, you may need to take a screenshot of the screen which itself contains a child <em>SupportMapFragment </em>to share with others or save it for later use. In this article, we’ll discuss a common issue when taking a screenshot of a <em>SupportMapFragment </em>and the solution to fix it.</p><p><strong>Problem:<br></strong>When we try to export a bitmap screenshot of an activity that contains a <em>SupportMapFragment </em>inside it, we may sometimes get the correct bitmap showing every other view of the activity correctly, but the content of the <em>SupportMapFragment </em>is missing and appears as a black screen.</p><p><strong>Solution:<br></strong>There might be plenty of ways to fix this. But here is one way to fix it using and overlapping ImageView.<br>To solve this issue, we can use an ImageView that is overlapped onto the <em>SupportMapFragment </em>in the XML file. This ImageView will initially be invisible, but when the SupportMapFragment is ready, we can use the <em>onSnapshotReadyCallback </em>of the <em>SupportMapFragment </em>to get the screenshot of the <em>SupportMapFragment </em>and show it on the ImageView. Here’s how:</p><ol><li>Add an ImageView in the XML file that overlaps the <em>SupportMapFragment</em>.</li></ol><pre>&lt;FrameLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;MapView<br>        android:id=&quot;@+id/map_view&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;/&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/map_screenshot&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:visibility=&quot;invisible&quot;/&gt;<br><br>&lt;/FrameLayout&gt;</pre><p>2. In the Kotlin code, get the <em>SupportMapFragment </em>and ImageView.</p><pre>val mapView = findViewById(R.id.map_view);<br>val mapScreenshot = findViewById(R.id.map_screenshot);</pre><p>3. Override the <em>onMapReady </em>callback and set the <em>onSnapshotReadyCallback</em>.</p><pre>mapView.getMapAsync(OnMapReadyCallback {<br>            mapView.snapshot(SnapshotReadyCallback { bitmap -&gt;<br>                mapScreenshot.setImageBitmap(bitmap)<br>                mapScreenshot.setVisibility(View.VISIBLE)<br>                mapView.setVisibility(View.INVISIBLE)<br>            })<br>})</pre><p>4. Take the screenshot of the activity.</p><pre>private fun takeScreenshot() {<br>        val rootView = window.decorView.rootView<br>        rootView.isDrawingCacheEnabled = true<br>        val bitmap = Bitmap.createBitmap(rootView.drawingCache)<br>        rootView.isDrawingCacheEnabled = false<br><br>        // Save the screenshot to a file<br>        // ...<br>    }</pre><p>Now, when the button is pressed, invoking the above method, the screenshot will include the content of the <em>SupportMapFragment</em>.</p><p><strong>Conclusion :<br></strong>Taking a screenshot of a <em>SupportMapFragment </em>in Android can sometimes be a challenging task, but by using an overlapping ImageView, we can overcome this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2d1284f48a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>