<?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 Raja Bhandari on Medium]]></title>
        <description><![CDATA[Stories by Raja Bhandari on Medium]]></description>
        <link>https://medium.com/@rajabhandari100?source=rss-3a7d70739aa6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ec8dBPCZjs7SqDGheZFuFQ.png</url>
            <title>Stories by Raja Bhandari on Medium</title>
            <link>https://medium.com/@rajabhandari100?source=rss-3a7d70739aa6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:22:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajabhandari100/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[Storing Secrets in the NDK (Without Losing Your Mind)]]></title>
            <link>https://medium.com/@rajabhandari100/storing-secrets-in-the-ndk-without-losing-your-mind-c13d550d34d8?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13d550d34d8</guid>
            <category><![CDATA[android-ndk]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[mobile-security]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 15:02:02 GMT</pubDate>
            <atom:updated>2025-12-02T15:02:02.914Z</atom:updated>
            <content:encoded><![CDATA[<h4>Smuggling sensitive data past curious APK explorers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzWZxSmCAO_ddXL6b4CoIQ.png" /></figure><p>If you’ve ever wondered <em>“Can I hide my API key somewhere so it’s not sitting in plain Kotlin like a neon sign?”, </em>then<em> </em>welcome. This post is the friendly, step‑by‑step guide I wish I had when I first heard and explored the NDK.</p><p>We’re going to build a tiny project where:</p><ul><li>we store an API key inside <strong>native C++</strong>,</li><li>we retrieve it from <strong>Kotlin</strong>, and</li><li>we keep the whole process simple, and logical (Atleast, I try to :P)</li></ul><p>This is not military‑grade protection, but then it’s miles better than <strong>hardcoding</strong> secrets in Kotlin.</p><h3>⚡ Why even use the NDK for storing stuff?</h3><p>Android apps are <strong><em>easy to decompile</em></strong>. If your API key sits in Kotlin like:</p><pre>val apiKey = &quot;MY_VERY_SECRET_KEY_123_LOOK_HEREEE_PLEASEEEEEEE&quot;</pre><p>you can bet someone can extract it in under 5 seconds.</p><p>But when you compile C++ into a .so file (native library):</p><ul><li>strings become harder to find,</li><li>the compiled binary is harder to inspect,</li><li>and casual attackers give up much earlier.</li></ul><p>Again, not bulletproof….but in many “demo app” or “light-security” cases, this is <em>exactly</em> what you need.</p><h3>🎯 What we’re building (in plain English)</h3><p>We’re going to:</p><ol><li>Write <strong>C++ code</strong> that holds an <em>encrypted</em> API key.</li><li>Decrypt it inside C++ at runtime.</li><li>Return it to Kotlin using JNI.</li><li>Use it normally in our Android app.</li></ol><p>And we’ll walk through every step as if we’re building it together.</p><h3>🌳 Project File Tree</h3><pre>app/<br> ├─ src/main/<br> │   ├─ java/com/example/ndkstore/<br> │   │   ├─ NativeLib.kt<br> │   │   └─ MainActivity.kt<br> │   ├─ cpp/<br> │   │   └─ native-lib.cpp<br> │   └─ AndroidManifest.xml<br> ├─ CMakeLists.txt<br> └─ build.gradle (module: app)<br>settings.gradle (root)<br>build.gradle (root)</pre><h3>🚀 Step 1 : Create your Kotlin class that talks to native code</h3><p>We start from Kotlin because it’s the most familiar ground.<br>Create a file: NativeLib.kt</p><pre>object NativeLib {<br>    init {<br>        System.loadLibrary(&quot;native-lib&quot;)<br>    }<br>    <br>    // JNI binding - implemented in native-lib.cpp<br>    external fun getApiKey(): String<br>}</pre><h4>Why are we doing this?</h4><ul><li>System.loadLibrary(&quot;native-lib&quot;) loads your native libnative-lib.so into memory.</li><li>external fun getApiKey() tells Kotlin “this function is actually implemented in C++”.</li><li>object ensures it&#39;s loaded once and reused.</li></ul><p>That’s it. Kotlin is ready.</p><h3>🔧 Step 2 : Write the native C++ function that returns the API key</h3><p>This is the heart of the whole feature.<br>Create: app/src/main/cpp/native-lib.cpp</p><pre>// Required JNI header - provides JNIEnv, jstring, and JNI functions<br>#include &lt;jni.h&gt;<br><br>// For std::string and basic string operations<br>#include &lt;string&gt;<br><br>extern &quot;C&quot;<br>JNIEXPORT jstring JNICALL<br>Java_com_example_ndkstore_NativeLib_getApiKey(JNIEnv *env, jobject) {<br><br>    // This array contains the encrypted API key.<br>    // The key was XOR-encrypted before storing here.<br>    // Example plaintext -&gt; XOR with 0x5A -&gt; produce these bytes.<br>    static const unsigned char encrypted[] = {<br>            9, 27, 23, 10, 22, 31, 5, 27, 10, 19,<br>            5, 17, 31, 3, 5, 107, 104, 105, 110, 111<br>    };<br><br>    // The same XOR value used during encryption.<br>    // Decryption simply XORs the encrypted bytes again with the same key.<br>    const unsigned char xorKey = 0x5A;<br><br>    // Total number of bytes in the encrypted array.<br>    size_t len = sizeof(encrypted);<br><br>    // std::string is used to build the decrypted API key.<br>    // Reserve memory ahead of time to avoid reallocations.<br>    std::string decrypted;<br>    decrypted.reserve(len);<br><br>    // Loop through each encrypted byte and decrypt it.<br>    for (size_t i = 0; i &lt; len; ++i) {<br>        // XOR with the same key reverses the encryption.<br>        decrypted.push_back(encrypted[i] ^ xorKey);<br>    }<br><br>    // Convert the std::string into a Java jstring<br>    // so we can return it back to Kotlin.<br>    return env-&gt;NewStringUTF(decrypted.c_str());<br>}</pre><h4>Let’s break this down like humans:</h4><ul><li>We <strong>don’t</strong> store the API key as plain text. Instead, <strong><em>we store encrypted bytes </em></strong>here.</li><li>At runtime, we decrypt them with a simple XOR operation.</li><li>Then we return the decrypted result as a Kotlin String.</li></ul><h4>But… Why XOR?</h4><p>Because it’s:</p><ul><li>dead simple,</li><li>reversible,</li><li>just enough to stop string scanners.</li></ul><p>You can replace it with any custom algorithm later.</p><h3>🧱 Step 3 : Tell Gradle how to build native code</h3><p>Create this file: CMakeLists.txt</p><pre>cmake_minimum_required(VERSION 3.10.2)<br>project(&quot;ndkstore&quot;)<br><br>add_library( # name of the native library<br>        native-lib<br><br>        # library type: shared so System.loadLibrary() works<br>        SHARED<br><br>        # source file path here<br>        src/main/cpp/native-lib.cpp<br><br>        #----- add other .cpp files if present/required -----<br>)</pre><h4>Why this file exists</h4><p>CMake tells Android Studio:</p><ul><li>which native files to compile,</li><li>what the output library should be called,</li><li>which system libs you want to reference.</li></ul><p>You don’t need to modify this unless you’re doing something advanced.</p><blockquote>Note: The <strong>location </strong>of this file<strong> </strong>can change, but the <strong>name cannot</strong>.</blockquote><h3>⚙️ Step 4 : Enable NDK in build.gradle</h3><p>Inside your <strong>app module</strong> build.gradle:</p><pre>android { <br>    externalNativeBuild {<br>        cmake {<br>            path = File(&quot;CMakeLists.txt&quot;)<br>        }<br>    }<br>}</pre><p>This tells Gradle:</p><blockquote><em>“Yes, this app uses C++. So, please build it too.”</em></blockquote><p>Nothing fancy here.</p><h3>🖥️ Step 5 : Actually using the API Key in Kotlin</h3><p>In MainActivity.kt:</p><pre>class MainActivity : AppCompatActivity() {<br><br>    // NOTE: calling native function from Kotlin<br>    private val apiKey: String by lazy { NativeLib.getApiKey() }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContentView(R.layout.activity_main)<br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -&gt;<br>            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())<br>            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)<br>            insets<br>        }<br><br>        val tvKey = findViewById&lt;TextView&gt;(R.id.tvKey)<br><br>        tvKey.text = &quot;API Key from NDK:\n$apiKey&quot;<br>    }<br>}</pre><p>Here’s what’s happening:</p><ul><li>Kotlin calls the native getApiKey() function.</li><li>The key comes back decrypted.</li><li>We show it on screen (just to prove it’s working).</li></ul><p>In a real app, you’d pass it to an API client instead.</p><h3>🔐 Step 6 : How to change the API key (super easy)</h3><p>Here’s the flow:</p><h4>1️⃣ Pick your new key</h4><p>Example:</p><pre>MY_SECRET_98765</pre><h4>2️⃣ Run this small Python script</h4><pre>plaintext = &quot;MY_SECRET_98765&quot;<br>xor = 0x5A<br>encrypted = [ord(c) ^ xor for c in plaintext]<br>print(encrypted)</pre><h4>3️⃣ Copy the output into the encrypted[] array in C++</h4><p>That’s it.</p><p>Android Studio recompiles → the new key is embedded inside the .so binary.</p><h3>🧠 A note on security (quick &amp; honest)</h3><p>Storing a secret in C++:</p><ul><li><strong>helps against casual attackers</strong>,</li><li><strong>prevents basic string scanning</strong>,</li><li><strong>raises the effort required</strong>, but…</li><li><strong>it does NOT stop determined reverse engineers</strong>.</li></ul><p>If your key is truly sensitive:</p><ul><li>keep it on a backend,</li><li>issue short-lived tokens,</li><li>use certificate pinning.</li></ul><p>But for API keys in sample apps, demos, hobby projects, prototype SDKs?<br>This method is <em>perfect</em>.</p><h3>🤔 What more can I do?</h3><p>When developers use the NDK for storing an API key, it’s usually because they want to move something sensitive out of the easily readable Kotlin layer. But this idea applies to much more than just keys.</p><p>In real-world apps, teams often place a variety of values and logic in native code because <strong>compiled C++ is harder to inspect than .dex files</strong>. Here are some common examples that I found while reading more about the use-cases:</p><ul><li><strong>Feature unlock flags or internal switches: </strong>Small booleans that enable hidden menus, beta features, or developer tools are often moved to the NDK so they can’t be toggled by simply editing a smali file.</li><li><strong>Configuration values that reveal app logic: </strong>Strings that control behavior, private error messages, or custom command triggers are less obvious when stored in native binaries.</li><li><strong>Anti-tamper or integrity checks: </strong>Root detection, package signature checks, checksum validation, and environment verification are frequently placed in C++ to make them harder to patch out.</li><li><strong>Proprietary formulas or data tables: </strong>Apps that rely on unique scoring systems, audio/video processing tweaks, or lookup tables often shift those pieces into native code to deter cloning.</li><li><strong>DRM-related values or lightweight license checks: </strong>Basic entitlement checks or simple offline validation logic sometimes live in NDK code for an extra layer of friction.</li></ul><p>None of these become truly secure by moving them into the NDK, but they become significantly <strong>harder to extract or modify compared to leaving them in plain Kotlin</strong>. And in many cases, that added friction is exactly what the development team needs.</p><blockquote>Thumb Rule: Use NDK to store <strong>values you want to hide</strong>, not <strong>values you must protect with 100% security</strong>. If the value is meant to run in client-side code and you just want to avoid easy decompiling, NDK is perfect!</blockquote><h3>🎉 Final thoughts</h3><p>Working with the NDK often feels like stepping behind the curtain of Android, and that’s exactly what makes this approach so practical. You’re taking something sensitive (like an API key), and instead of leaving it exposed in your Kotlin code, you tuck it deeper into the system where it’s less obvious and harder to casually grab.</p><p>Sure, it’s not bulletproof as I have mentioned time and again. <strong>Nothing stored on a client device ever is</strong>. But it <em>meaningfully</em> raises the barrier, and that’s the entire point: make things just difficult enough that anyone trying to poke around will think twice.</p><p>For many apps, such as demos, internal tools, prototypes, hobby projects; this technique is the perfect balance of effort, usability, and protection. And once you understand the flow from Kotlin → JNI → C++ → back to Kotlin, the whole Android platform starts to feel a lot more powerful.</p><p>It’s a good reminder that as Android developers, we’re not limited to just Kotlin or Java. Sometimes, dropping down a layer gives you exactly the control you need.</p><p>📎 Check out the Github project here, and let me know your thoughts: <a href="https://github.com/IamRaja007/NDKStore">https://github.com/IamRaja007/NDKStore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13d550d34d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MVVM in Android: The Rise of Reactive UIs]]></title>
            <link>https://medium.com/@rajabhandari100/understanding-mvvm-in-android-the-rise-of-reactive-uis-e2e30404c962?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e30404c962</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 15:58:05 GMT</pubDate>
            <atom:updated>2025-11-05T15:58:26.043Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How MVVM made Android apps cleaner, smarter, and truly lifecycle-aware.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNruRvHBsfcxccUdBdlCLQ.png" /></figure><p>If you’ve read my previous article on <a href="https://medium.com/@rajabhandari100/understanding-mvp-in-android-taking-control-back-from-the-monster-activity-a21ae496b03e">MVP</a>, you might remember how that pattern helped us tame the “Monster Activity” by splitting responsibilities into Model, View, and Presenter.</p><p>But as apps grew larger, MVP started showing some cracks. The manual wiring between View and Presenter became repetitive, and updating the UI reactively felt clunky.</p><p>Developers wanted a cleaner way to connect data and UI, like you know <strong>without all the glue code. </strong>That’s where <strong>MVVM (Model–View–ViewModel)</strong> entered the picture.</p><h3>🧭 What MVVM Actually Means</h3><p>Like MVP, <strong>MVVM</strong> divides your app into 3 familiar layers, but it changes <strong><em>how</em></strong> they talk to each other.</p><ul><li><strong>Model</strong><br>Just like before, it handles data and business logic such as fetching, saving, validating, and all that good stuff.</li><li><strong>View</strong><br>Your Activity, Fragment, or Custom View. It displays data and handles user interactions, but doesn’t touch the Model directly. Instead, it <strong>observes data</strong> from the ViewModel.</li><li><strong>ViewModel</strong><br>This is where the real magic happens. It acts as a bridge between the View and Model, but unlike the Presenter, it <strong>doesn’t hold a reference to the View</strong>. Instead, it exposes <strong>observable data streams</strong> (like LiveData or Observable), which the View simply listens to and reacts when the data changes.</li></ul><p>Here’s the big mindset shift:</p><blockquote><em>The Presenter </em>calls<em> the View, while the ViewModel </em>notifies<em> the View through data changes.</em></blockquote><p>It’s an <strong>event-driven, reactive approach</strong>, where the ViewModel produces data, and the View consumes it.</p><p>No callbacks. No tight coupling. Just data flowing one way.</p><h3>⚙️ How Android Embraced MVVM</h3><p>In the Android world:</p><ul><li><strong>Activities/Fragments/Custom Views</strong> → act as the <strong>View</strong></li><li><strong>ViewModel</strong> → holds all presentation logic, fetches/updates data</li><li><strong>LiveData</strong> or <strong>Flow/Observable</strong> → are the communication channels between them</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*_MUxxVUoCDZWVoaLDHhQaA.png" /></figure><p>When something changes in the ViewModel, say, a login succeeds; then the View automatically gets notified via LiveData observers and updates the UI.</p><p><strong>No need</strong> for the ViewModel to manually call view.showSuccess() like in MVP.</p><p>That’s what makes it clean, testable, and lifecycle-aware.</p><h3>🧩 Step 1: ViewModel + LiveData Setup</h3><p>Let’s revisit our Login example from the MVP article, but this time, in MVVM style.</p><p>Here, our ViewModel handles the login logic and exposes <strong>observable states</strong> for the View to react to.</p><pre>class LoginViewModel(<br>    private val repository: LoginRepository<br>) : ViewModel() {<br><br>    private val _loginStatus = MutableLiveData&lt;LoginStatus&gt;()<br>    val loginStatus: LiveData&lt;LoginStatus&gt; get() = _loginStatus<br><br>    fun login(username: String, password: String) {<br>        _loginStatus.value = LoginStatus.Loading()<br><br>        viewModelScope.launch {<br>            try {<br>                val success = repository.login(username, password)<br>                if (success) {<br>                    _loginStatus.value = LoginStatus.Success()<br>                } else {<br>                    _loginStatus.value = LoginStatus.Error()<br>                }<br>            } catch (e: Exception) {<br>                _loginStatus.value = LoginStatus.Error()<br>            }<br>        }<br>    }<br>}<br><br><br>class LoginViewModelFactory(<br>    private val repository: LoginRepository<br>) : ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(LoginViewModel::class.java)) {<br>            @Suppress(&quot;UNCHECKED_CAST&quot;)<br>            return LoginViewModel(repository) as T<br>        }<br>        throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}</pre><p>And our LoginStatus class defines what states we might want to display:</p><pre>sealed class LoginStatus {<br>    class Loading : LoginStatus()<br>    class Success : LoginStatus()<br>    class Error : LoginStatus()<br>}</pre><p>Notice something here? There’s <strong>no reference to any View or Activity. </strong>This ViewModel <em>doesn’t even know it’s part of an Android app</em>.</p><p>That’s why it’s easily testable you know, just like a plain Kotlin class.</p><h3>🖼️ Step 2: Implementing the View (Activity)</h3><p>The Activity now focuses only on UI, subscribing to the ViewModel’s LiveData.</p><pre>class LoginActivity : AppCompatActivity() {<br><br>    private lateinit var binding: ActivityLoginBinding<br>    private lateinit var viewModel: LoginViewModel<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityLoginBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br><br>        viewModel = ViewModelProvider(<br>            this,<br>            LoginViewModelFactory(LoginRepository())<br>        )[LoginViewModel::class.java]<br><br>        viewModel.loginStatus.observe(this) { status -&gt;<br>            when (status) {<br>                is LoginStatus.Loading -&gt; binding.status.text = &quot;Loggin in...&quot;<br>                is LoginStatus.Success -&gt; binding.status.text = &quot;Login success!&quot;<br>                is LoginStatus.Error -&gt; binding.status.text = &quot;Invalid credentials&quot;<br>            }<br>        }<br><br>        binding.loginButton.setOnClickListener {<br>            val username = binding.username.text.toString()<br>            val password = binding.password.text.toString()<br>            <br>            viewModel.login(username, password)<br>        }<br>    }<br>}</pre><p>So now, instead of the Presenter calling showLoginSuccess(), the View just <strong>reacts</strong> to state changes <strong>automatically</strong>.</p><h3>⚖️ MVP vs MVVM: The Evolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiKSVKWQUpCl10Ciw3AyQg.png" /></figure><p>In short, <strong>MVVM keeps all the benefits of MVP</strong> such as structure, clarity, and testability, but makes it more <strong>reactive and lifecycle aware</strong>.</p><ul><li>No more manual attach/detach calls.</li><li>No more memory leaks from holding View references.</li><li>Just clean data-driven UI updates.</li></ul><h3>🧠 Under the Hood: Reactive Power</h3><p>MVVM became especially powerful once Android introduced <strong>Architecture Components</strong>, particularly:</p><ul><li>ViewModel→ survives configuration changes like rotations</li><li>LiveData→ automatically observes lifecycle and cleans itself up</li></ul><p>Before that, developers often relied on RxJava/RxKotlin to achieve similar reactivity by subscribing and unsubscribing manually in onResume() and onPause().</p><p>With LiveData, that’s handled for you:</p><blockquote><em>Observe once in </em><em>onCreate(), and you’re done.<br>LiveData </em><strong><em>automatically</em></strong><em> stops observing when your Activity or Fragment is destroyed.</em></blockquote><p>That’s the real superpower of MVVM: <strong>reactivity without the headache! :)</strong></p><h3>🧪 Testing the ViewModel</h3><p>Testing is simple since our LoginViewModel has <strong>no Android dependencies</strong>.</p><pre>class LoginViewModelTest {<br><br>    @get:Rule<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    @Test<br>    fun `should emit Loading and Success when login succeeds`() = runTest {<br>        val fakeRepository = object : LoginRepository() {<br>            override suspend fun login(username: String, password: String): Boolean {<br>                return true //succeeding always<br>            }<br>        }<br><br>        val viewModel = LoginViewModel(fakeRepository)<br>        val results = mutableListOf&lt;LoginStatus&gt;()<br><br>        viewModel.loginStatus.observeForever { results.add(it) }<br><br>        viewModel.login(&quot;admin&quot;, &quot;12345&quot;)<br><br>        advanceUntilIdle() <br><br>        assertTrue(results.first() is LoginStatus.Loading)<br>        assertTrue(results.last() is LoginStatus.Success)<br>    }<br>}</pre><p>No Activity, no instrumentation test; just we are doing pure logic verification.</p><h3>📝 Key Takeaways</h3><ul><li>MVVM evolved from MVP to eliminate the manual wiring between View and Presenter.</li><li>The <strong>ViewModel</strong> exposes observable data streams (LiveData, Flow, or Observables).</li><li>The <strong>View</strong> simply observes data and reacts with no more direct method calls.</li><li><strong>Lifecycle awareness</strong> is built-in, avoiding leaks or redundant updates.</li><li>Testing is simpler, since ViewModels are plain Kotlin classes.</li><li>Cleaner, reactive, and less boilerplate. That’s MVVM in action.</li></ul><h3>👋 Wrapping Up</h3><p>MVP gave us structure and separation of concerns.<br>MVVM took it a step further by <strong>bringing reactivity, lifecycle awareness, and even cleaner architecture</strong>.</p><p>But that’s not the end of the journey. Mind it.<br>As apps scaled, developers started combining MVVM with <strong>coroutines, flows, and state management patterns</strong> like MVI (Model–View–Intent) to achieve even more predictability and unidirectional data flow.</p><p>Stay tuned for the next article where we’ll see how MVI brings a whole new level of clarity to modern Android apps. 🚀</p><blockquote>Did you know: <strong>You can clap upto 50 times on a Medium article! Just long press that little clap icon. Try it!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e30404c962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MVP in Android: Taking Control Back from the Monster Activity]]></title>
            <link>https://medium.com/@rajabhandari100/understanding-mvp-in-android-taking-control-back-from-the-monster-activity-a21ae496b03e?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21ae496b03e</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 18:27:12 GMT</pubDate>
            <atom:updated>2025-10-29T18:28:19.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how MVP brings structure, clarity, and testability to Android apps.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCpHwMkbWvZPN3nFIVDjRQ.png" /><figcaption>The Monster Activity is way scarier than this depicted image :D</figcaption></figure><p>If you read my previous article on <a href="https://medium.com/@rajabhandari100/understanding-mvc-in-android-where-it-all-began-2e4421a82cc6"><strong>MVC</strong></a>, you’ll remember how Android’s early apps often ended up with <em>Massive Activities, </em>where UI, data, and logic all lived together in one noisy class.</p><p>Developers wanted to fix that mess without reinventing the wheel.<br>That’s where <strong>MVP (Model-View-Presenter)</strong> stepped in, as a more structured evolution of MVC, designed to fit Android’s quirks.</p><h3>🧭 What MVP Actually Means</h3><p>MVP, or <strong>Model-View-Presenter</strong>, divides the app into 3 familiar parts; but this time, the communication lines are stricter.</p><ul><li><strong>Model</strong><br>Just like in MVC, it handles data and business logic (fetching, saving, validating, etc.)</li><li><strong>View</strong><br>Displays information and handles user input, but this time, it <strong>does not talk to the Model directly</strong>. Instead, here it delegates everything to the Presenter.</li><li><strong>Presenter</strong><br>Its the smart middleman. It listens to the View’s actions, updates the Model, and decides <em>what</em> and <em>how</em> to show things back to the View.</li></ul><p>So the flow now looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*mAnHtVw0a45G-sg0i5btmA.png" /></figure><p>Each layer knows only what it should, hence keeping things loosely coupled and far more testable.</p><h3>📱 How Android Applied MVP</h3><p>In Android’s MVP world:</p><ul><li><strong>Activities, Fragments, or Custom Views</strong> act as the <strong>View layer</strong>.</li><li><strong>Presenter</strong> becomes a standalone class (no Android dependencies).</li><li>The <strong>View</strong> notifies the Presenter of user interactions.</li><li>The <strong>Presenter</strong> talks to the Model and updates the View accordingly (No direct link between View and Model)</li></ul><p>This change means our Activity can finally stop trying to do everything at once.</p><p>Let’s see how that looks using the same login example we used in the MVC article.</p><h3>🧩 Step 1: Define the Contract</h3><p>To keep things clean and testable, we define <strong>interfaces</strong> for both the View and the Presenter.<br>This is often called a <em>contract</em> between the two layers.</p><pre>interface LoginView {<br>    fun showLoginSuccess()<br>    fun showLoginError()<br>    fun showLoading()<br>}<br><br>interface LoginPresenter {<br>    fun onLoginClicked(username: String, password: String)<br>}</pre><ul><li>The View exposes methods for UI updates.</li><li>The Presenter exposes methods for user actions.</li></ul><p>Neither knows <em>how</em> the other works, it just knows <em>what</em> to call!</p><h3>🧠 Step 2: Implement the Presenter</h3><p>Here’s the Presenter logic. We can see that it contains no Android dependencies.</p><pre>class LoginPresenterImpl(<br>        private val view: LoginView,<br>        private val userRepository: UserRepository<br>) : LoginPresenter {<br>        <br>        override fun onLoginClicked(username: String, password: String) {<br>            view.showLoading()<br>            <br>            val success = userRepository.login(username, password)<br>            <br>            if (success) {<br>                view.showLoginSuccess()<br>            } else {<br>                view.showLoginError()<br>            }<br>        }<br>}</pre><p>The Presenter handles all the logic:</p><ul><li>Triggers a loading state on the View.</li><li>It receives input from the View.</li><li>Delegates authentication to the Model (via UserRepository).</li><li>Then tells the View about the outcome (what to display).</li></ul><h3>🖼️ Step 3: Implement the View (Activity)</h3><p>Our Activity now focuses purely on the UI.<br>No more business logic, and no direct Model access. Just clean separation.</p><pre>class LoginActivity : AppCompatActivity(), LoginView {<br>     private lateinit var presenter: LoginPresenter<br>     private lateinit var username: EditText<br>     private lateinit var password: EditText<br>     private lateinit var status: TextView<br>     private lateinit var loginButton: Button<br>        <br>     override fun onCreate(savedInstanceState: Bundle?) {<br>         super.onCreate(savedInstanceState)<br>         setContentView(R.layout.activity_login)<br>            <br>         username = findViewById(R.id.username)<br>         password = findViewById(R.id.password)<br>         status = findViewById(R.id.status)<br>         loginButton = findViewById(R.id.loginButton)<br>         presenter = LoginPresenterImpl(this, UserRepository())<br>            <br>         loginButton.setOnClickListener {<br>             presenter.onLoginClicked(<br>                username.text.toString(),<br>                password.text.toString()<br>             )<br>         }<br>      }<br><br>      override fun showLoginSuccess() {<br>          status.text = &quot;Login success&quot;<br>      }<br><br>      override fun showLoginError() {<br>          status.text = &quot;Invalid credentials&quot;<br>      }<br><br>      override fun showLoading() {<br>          status.text = &quot;Logging in...&quot;<br>      }<br>}</pre><p>Compared to the MVC version, our LoginActivity no longer mixes UI with logic, it just forwards events and updates views.</p><h3>🧩 Step 4: Presenter Lifecycle Awareness</h3><p>When using MVP, the View often triggers Presenter actions when it’s ready to display data.</p><p>For example, you might call:</p><pre>presenter.onLoad()</pre><p>inside onResume(), to fetch user data.</p><p>And:</p><pre>presenter.onStopLoading()</pre><p>inside onPause(), to cancel background work.</p><p>This ensures your Presenter isn’t doing work when the View is not visible, preventing leaks or wasted operations.</p><p>For custom views, you’d typically use:</p><ul><li>onAttachedToWindow() → start loading</li><li>onDetachedFromWindow() → stop loading</li></ul><h3>⚖️ MVC vs MVP: The Real Difference</h3><p>The biggest shift from <strong>MVC</strong> to <strong>MVP</strong> is <strong>who talks to whom</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_Y-zfMPSv0q-j4qGugkqQ.png" /></figure><p>MVP actually clears the confusion around <strong>UI logic</strong>.</p><p>In MVC, it was unclear whether UI formatting or conditional display logic belonged in the View or Controller. Whereas, in MVP, that responsibility lies squarely with the Presenter.</p><p><strong>However, there’s a caveat:</strong><br>If your Presenter tries to handle <em>everything, </em>from<em> </em>business logic to UI formatting to data transformation, then it can quickly turn into a <strong>God class</strong>, bloated and hard to maintain.</p><p>To prevent that, we need to delegate specific responsibilities to smaller helpers (helper classes with single responsibilities).</p><p>For example:</p><pre>class AddressFormatter {<br>    fun format(address: Address): String {<br>        return &quot;${address.street}, ${address.number}, ${address.zipCode}&quot;<br>    }<br>}</pre><p>Inject such formatters or utilities into your Presenter instead of letting it handle every detail.<br>This keeps your Presenter modular, focused and testable.</p><h3>🧪 Testing the Presenter</h3><p>Since our Presenter is a plain Kotlin class, testing it is a breeze.</p><p>Here’s how we can test if the Presenter correctly shows the loading state:</p><pre><br>@Test<br>fun `should show loading when login starts`() {<br>     var didShowLoading = false<br><br>     val fakeView = object : LoginView {<br>          override fun showLoginSuccess() {}<br>          override fun showLoginError() {}<br>          override fun showLoading() {<br>              didShowLoading = true<br>          }<br>      }<br><br>      val fakeRepository = object : UserRepository() {<br>           override fun login(username: String, password: String): Boolean {<br>               return true<br>           }<br>        }<br><br>       val presenter = LoginPresenterImpl(fakeView, fakeRepository)<br>       presenter.onLoginClicked(&quot;adminn&quot;, &quot;123456&quot;)<br><br>       assertTrue(didShowLoading)<br>}</pre><p>No need to spin up an Activity or use instrumentation tests.</p><p>You just pass in fake implementations and verify that the correct methods were called.</p><h3>📝 Key Takeaways</h3><ul><li>MVP refines MVC by <strong>removing the direct link</strong> between View and Model.</li><li>The Presenter owns all the UI logic and acts as the single source of truth for presentation.</li><li>Activities and Fragments become lean, focused only on displaying data and forwarding actions.</li><li>Testing becomes simple, since Presenters are plain Kotlin classes here.</li><li>Avoid the <strong>God Presenter</strong> trap by delegating responsibilities into helper classes.</li></ul><h3>👋 So, What’s Next</h3><p>MVP gave Android developers structure and testability, but it still required a lot of <strong>manual wiring</strong> between View and Presenter.<br>As apps grew more complex, developers wanted <strong>reactive UIs</strong> that could update automatically when data changed.</p><p>That evolution gave us <strong>MVVM (Model-View-ViewModel), </strong>where <strong>data binding</strong> and <strong>lifecycle awareness</strong> finally made UIs truly <strong>reactive</strong>.</p><p>Stay tuned for the next article! Enjoyed this article? Do comment. It keeps me motivated :)</p><blockquote>Did you know: <strong>You can clap 50 times on Medium! Just long press that little clap icon. Try it!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21ae496b03e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MVC in Android: Where It All Began]]></title>
            <link>https://medium.com/@rajabhandari100/understanding-mvc-in-android-where-it-all-began-2e4421a82cc6?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4421a82cc6</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 14:40:02 GMT</pubDate>
            <atom:updated>2025-10-27T19:03:57.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy2hZSg2qnyOeH-oVsLD1A.png" /></figure><p>Every good story has an origin. For Android architecture, that story starts with <strong>MVC</strong>.<br>If you have ever worked on a legacy Android app and found all the UI code, networking, and database calls packed into a single MainActivity, you have witnessed MVC in its earliest (and sometimes messiest) form.</p><p>Before modern patterns like MVP, MVVM, and MVI entered the scene, <strong>Model-View-Controller</strong> was the go-to structure. It made sense in theory, but Android’s early implementation was a bit like trying to fit a square peg into a round hole.</p><p>Let’s unpack what MVC actually is, how it was applied in Android, what problems it created, and how developers tried to fix it.</p><h3>🧭 What MVC Actually Means</h3><p>The <strong>Model-View-Controller</strong> pattern splits your application into three distinct parts:</p><ul><li><strong>Model</strong><br>This layer represents the data and the business logic. It can involve fetching data from the network, saving it in a database, or applying business rules.</li><li><strong>View</strong><br>This layer handles what the user sees. It should focus on displaying information and receiving user interactions, without containing business logic.</li><li><strong>Controller</strong><br>This layer acts as the bridge. It listens to user input from the View, updates the Model, and then instructs the View to refresh.</li></ul><p>Here is an illustration of the flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*26st3fxNVwiJDVwdcuwUIw.png" /></figure><p>The key idea is <strong>separation of concerns</strong>. Each layer does one job, which makes the code more maintainable and testable.</p><h3>📱 How Android Adopted MVC (Early Days)</h3><p>In theory, MVC is great. In early Android, though, <strong>Activities</strong>, <strong>Fragments</strong>, and <strong>Custom Views</strong> were often treated as both <strong>View</strong> and <strong>Controller</strong> at the same time.</p><p>They would:</p><ul><li>Inflate layouts</li><li>Handle user clicks</li><li>Make network calls</li><li>Access the database</li><li>Update the UI</li></ul><p>All from inside a single class.</p><p>Here is a simple example of what that looked like.</p><pre>class LoginActivity : AppCompatActivity() {<br>   <br>    private val userRepository = UserRepository()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_login)<br>        <br>        val username = findViewById&lt;EditText&gt;(R.id.username)<br>        val password = findViewById&lt;EditText&gt;(R.id.password)<br>        val status = findViewById&lt;TextView&gt;(R.id.status)<br>        val loginButton = findViewById&lt;Button&gt;(R.id.loginButton)<br>        <br>        loginButton.setOnClickListener {<br>            // Business logic right in the Activity<br>            val success = userRepository.login(<br>                username.text.toString(),<br>                password.text.toString()<br>            )<br>            <br>            // UI update also here<br>            status.text = if (success) {<br>                &quot;Login success&quot;<br>            } else {<br>                &quot;Invalid credentials&quot;<br>            }<br>        }<br>    }<br>}</pre><p>This is fine for a quick demo you know, but real apps quickly become unmanageable with this pattern. One small change often means scrolling through hundreds of lines to find the right spot.</p><h3>🧨 The Big Problem: Massive Activities and Testing Pain</h3><p>The moment your Activity starts acting as both View and Controller, things start to go downhill.</p><ul><li><strong>Massive Activities</strong><br>Over time, these classes grow to thousands of lines because they handle too many responsibilities.</li><li><strong>Tight coupling</strong><br>UI code and business logic get tangled together, making refactoring risky.</li><li><strong>Hard to test</strong><br>You cannot easily unit test your business logic because it lives inside classes that depend on the Android framework. Spinning up an Activity in a unit test is slow and brittle.</li></ul><p>Developers started jokingly calling this approach <strong>Massive-View-Controller</strong>, because the Controller part basically swallowed everything else.</p><h3>🧠 The Attempted Fix: Introducing a Proper Controller</h3><p>To bring MVC closer to its original design, developers started separating <strong>Controller logic into its own class</strong>, while keeping Activities, Fragments, and custom Views strictly in the <strong>View layer</strong>.</p><p>Here is how the improved flow works:</p><ol><li>The View (Activity or Fragment) receives user input.</li><li>It notifies a separate Controller class.</li><li>The Controller updates the Model and tells the View to update.</li><li>The View fetches data from the Model and displays it.</li></ol><p>This way, Activities stop being monsters that know everything. The Controller becomes a plain Kotlin or Java class that is easier to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*N1v0JH1GxS4Vd-gESLsCSQ.png" /></figure><h3>✅ Example: Login with a Separate Controller</h3><h4>Step 1: Define a LoginView interface</h4><pre>interface LoginView {<br>    fun showLoginSuccess()<br>    fun showLoginError()<br>}</pre><p>This is a simple <strong>contract</strong> between the Controller and the View.</p><h4>Step 2: Create the LoginController</h4><pre>class LoginController(<br>    private val view: LoginView,<br>    private val userRepository: UserRepository<br>) {<br>    fun onLoginClicked(username: String, password: String) {<br>        val success = userRepository.login(username, password)<br>        <br>        if (success) {<br>            view.showLoginSuccess()<br>        } else {<br>            view.showLoginError()<br>        }<br>    }<br>}</pre><p>This class contains no Android dependencies, which makes it straightforward to test.</p><h4>Step 3: Implement the View in the Activity</h4><pre>class LoginActivity : AppCompatActivity(), LoginView {<br>    <br>    private lateinit var controller: LoginController<br>    private lateinit var username: EditText<br>    private lateinit var password: EditText<br>    private lateinit var status: TextView<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_login)<br>        <br>        username = findViewById(R.id.username)<br>        password = findViewById(R.id.password)<br>        status = findViewById(R.id.status)<br>        controller = LoginController(this, UserRepository())<br>        <br>        findViewById&lt;Button&gt;(R.id.loginButton).setOnClickListener {<br>            controller.onLoginClicked(<br>                username.text.toString(),<br>                password.text.toString()<br>            )<br>        }<br>    }<br><br>    override fun showLoginSuccess() {<br>        status.text = &quot;Login success&quot;<br>    }<br><br>    override fun showLoginError() {<br>        status.text = &quot;Invalid credentials&quot;<br>    }<br>}</pre><p>Now the Activity is focused only on UI. The Controller takes care of the logic, and the Model handles data.</p><h3>🧪 Testing the Controller</h3><p>Because the Controller <strong>does not</strong> depend on Android classes, you can test it with a simple fake View.</p><pre>class FakeLoginView : LoginView {<br>    var successCalled = false<br>    var errorCalled = false<br>        <br>    override fun showLoginSuccess() {<br>        successCalled = true<br>    }<br><br>    override fun showLoginError() {<br>         errorCalled = true<br>    }<br>}<br><br><br>class LoginControllerTest {<br>     @Test<br>     fun `should show success on valid login`() {<br>         val fakeView = FakeLoginView()<br>         val controller = LoginController(fakeView, UserRepository())<br>            <br>         controller.onLoginClicked(&quot;admin&quot;, &quot;12345&quot;)<br>            <br>         assertTrue(fakeView.successCalled)<br>         assertFalse(fakeView.errorCalled)<br>    }<br>}</pre><p>No Android components, no test harness, no pain.</p><h3>🧠 A Small Gotcha in MVC: Who Owns the UI Logic?</h3><p>One of the sneaky problems with MVC is that it never clearly says which layer should handle <strong>UI logic</strong>. Imagine you have a simple Address model:</p><pre>data class Address(<br>    val street: String,<br>    val number: String,<br>    val zipCode: String<br>)</pre><p>Now suppose you want to display it in the app as:</p><pre>Mahatma Gandhi Street, 12/b, 712160</pre><p>The simplest way might be to format it directly in your Activity:</p><pre>addressView.text =<br>    &quot;${address.street}, ${address.number}, ${address.zipCode}&quot;</pre><p>This works fine, but if you ever want to <strong>unit test this formatting</strong>, you’re stuck. Since the formatting lives inside the Activity (the View layer), the only way to test it is to run a UI test. UI tests are slower, more brittle, and harder to maintain than unit tests.</p><p>An alternative is to move the formatting into the Model:</p><pre>data class Address(<br>    val street: String,<br>    val number: String,<br>    val zipCode: String<br>) {<br>    val formattedAddress = &quot;$number, $street, $zipCode&quot;<br>}</pre><p>And then in the Activity:</p><pre>addressView.text = address.formattedAddress</pre><p>Now you can easily unit test the description property. But there’s a catch: your <strong>Model now knows how data should be presented in the UI</strong>, which breaks the separation of concerns. The Model is supposed to be about business logic and data, not formatting strings for the View.</p><p>This leads to a bigger issue: in MVC, the <strong>View knows too much</strong>. It knows the Controller, it knows the Model, and sometimes it even bypasses the Controller completely to talk directly to the Model. That’s like hiring a receptionist who occasionally walks into the accounting department to grab tax files herself. It works… until it doesn’t.</p><p>The solution is to <strong>avoid</strong> having a direct reference to the Model. Instead, everything should go through the Controller, and the Controller should handle the UI logic, knowing how to <strong><em>present</em></strong> the Model in the View. This is exactly the problem that <strong>MVP</strong> solves.</p><h3>📝 Key Takeaways</h3><ul><li>MVC was the first widely used architectural pattern in Android apps.</li><li>In practice, Activities and Fragments often acted as both View and Controller, which led to bloated classes and testing headaches.</li><li>Separating Controller logic into standalone classes and using interfaces for communication improves testability and maintainability.</li><li>While MVC laid the groundwork, it also exposed the need for patterns that better fit Android’s lifecycle and framework limitations.</li></ul><h3>👋 What’s Next</h3><p>In the next blog, we will look at <strong>MVP (Model-View-Presenter)</strong>, which builds on these ideas and formalises the separation between UI and logic even further. It involves fewer monster Activities and a lot more sanity.</p><p>Stay tuned. And if your current MainActivity looks like a spaghetti recipe, now might be a good time to introduce a Controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4421a82cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Views, Layouts & Optimizations (3)]]></title>
            <link>https://medium.com/@rajabhandari100/views-layouts-optimizations-3-0a4957037f82?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4957037f82</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ui-performance]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[android-xml]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 10:26:14 GMT</pubDate>
            <atom:updated>2025-10-14T17:23:53.091Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Secret Life of Android Views: RecyclerView Pooling, Lazy Inflation &amp; Advanced View Control</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OONeyZoQH5TDfwWbkrnUUw.png" /></figure><p>In <a href="https://medium.com/@rajabhandari100/views-layouts-optimizations-3aea727ff2cd">Part 1</a>, we unraveled the <strong>lifecycle of Views</strong> and learned how <strong>measure → layout → draw</strong> works. And in <a href="https://medium.com/@rajabhandari100/views-layouts-optimizations-14a73621504f">Part 2</a>, we explored <strong>hierarchy depth, flattening, ViewStub, </strong><strong>&lt;merge&gt;, and overdraw</strong>.</p><p>Now, in the final part of our blog series, it’s time to go deeper into some advanced topics and optimizations. We’ll cover <strong>RecyclerView pooling strategies, lazy view inflation, visibility toggles, efficient animations, and </strong>boundary control with <strong>clipChildren/clipToPadding</strong>. Let’s get hands-on with practical optimization strategies you can implement today.</p><h3>1. RecyclerView &amp; RecycledViewPool</h3><p>If you’ve ever made a <strong>carousel inside a vertical RecyclerView</strong>, you might notice <strong>janky horizontal scrolling</strong>. Why?</p><p>Each RecyclerView maintains its <strong>own internal pool of ViewHolders</strong>. This normally works for one list.<br>But, if you have multiple RecyclerViews(like carousels inside a vertical list) that show the same item types/layouts, you end up with <strong>duplicate pools</strong>, leading to:</p><ol><li>Redundant inflations</li><li>Higher memory usage</li><li>Slower scrolling</li></ol><h4>Shared RecycledViewPool to the rescue</h4><p>RecycledViewPool is a shared pool of <strong>ViewHolders</strong> between <strong>multiple RecyclerViews</strong>, and helps in reducing inflations and memory cost.</p><p><strong>Use case: <br></strong>Imagine a screen with <strong>multiple horizontal lists</strong> inside a vertical list. Each inner list reuses the <strong>same item layout. <br></strong>An UI like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ls5o_RkcczS9sC0OqjdfA.png" /></figure><p>Each inner Horizontal RecyclerView (1 &amp; 2) is a new instance and creates its own pool of recycled views, even though they are all using the exact same item layouts you know. And that means redundant inflations and higher memory usage.</p><p><strong>How to solve?<br></strong>Lets use <strong>RecycledViewPool</strong>.<br>So, if we share one common pool between all horizontal lists, then:<br>1. When you scroll Electronics off screen, its views go to the shared pool.<br>2. Now, when Books scrolls in, it can re-use those exact same views, thus reducing inflation cost and memory.</p><pre>class OuterAdapter(private val sharedPool: RecyclerView.RecycledViewPool) :<br>    RecyclerView.Adapter&lt;OuterAdapter.OuterViewHolder&gt;() {<br>    override fun onBindViewHolder(holder: OuterViewHolder, position: Int) {<br>        val innerRecyclerView = holder.itemView.findViewById&lt;RecyclerView&gt;(R.id.innerRecyclerView)<br>        innerRecyclerView.setRecycledViewPool(sharedPool)<br>        innerRecyclerView.adapter = InnerAdapter(getItemsForPosition(position))<br>    }<br>}</pre><p><strong>Things to Note:</strong></p><ul><li>Default pool keeps <strong>5 views per type</strong>. If needed, increase with:</li></ul><pre>sharedPool.setMaxRecycledViews(viewType = 0, max = 15)</pre><ul><li>Only reuse <strong>views of the same type</strong>. Different layouts must have separate entries.</li><li>Great for <strong>rapid horizontal scrolling</strong>, repeated item layouts, or nested carousels.</li></ul><h3>2. Lazy View Inflation</h3><p>Creating heavy views <strong>too early</strong> can slow down screen rendering. Lazy inflation helps by <strong>deferring creation until necessary</strong>.</p><h3>Techniques for lazy inflation</h3><h4><strong>1. ViewStub</strong></h4><ul><li>Lightweight placeholder that inflates only when needed.</li><li>You can read more about this in my <a href="https://medium.com/@rajabhandari100/views-layouts-optimizations-14a73621504f">part 2</a> blog.</li></ul><h4><strong>2. Manual Lazy Inflation</strong></h4><ul><li>Without ViewStub, you can still inflate views lazily yourself:</li></ul><pre>val container = findViewById&lt;LinearLayout&gt;(R.id.container)<br>val view = LayoutInflater.from(context)<br>    .inflate(R.layout.dynamic_content, container, false)<br>container.addView(view)</pre><blockquote>Very useful for:<br>a. Building complex UIs from config.<br>b. Dynamically adding sections.<br>c. Custom components.</blockquote><h4><strong>3. Avoid Early Inflation in Fragments</strong></h4><ul><li>Don’t inflate optional heavy views in onCreate() or onCreateView() (unless you absolutely need to).</li><li>Instead, you can use onViewCreated() to decide dynamically:</li></ul><pre>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>    if (shouldShowError) {<br>       showErrorView()<br>    }<br>}</pre><p>Or like,</p><pre>binding.buttonShowMore.setOnClickListener {<br>    if (binding.moreViewStub.parent != null) {<br>        binding.moreViewStub.inflate()<br>    }<br>}</pre><p><strong>Use cases:</strong> dynamic sections, error blocks, ads, or optional UI components.</p><h3>3. View Visibility: VISIBLE vs INVISIBLE vs GONE</h3><p>Understanding view visibility states is crucial for managing UI elements efficiently and creating smooth user experiences in Android applications.</p><h4>The Three Visibility States</h4><p><strong>a. View.VISIBLE</strong> → View is drawn and participates in layout calculations.</p><p><strong>b. View.INVISIBLE</strong> → View is NOT drawn but <strong>still reserves its space</strong> in the layout hierarchy.</p><p><strong>c. View.GONE</strong> → View is NOT drawn and does not occupy any space in the layout.</p><p>The setVisibility() method is used to apply these constants to any View.</p><h4>removeView() vs setVisibility(GONE)</h4><p>While both hide views from the user, they differ significantly in how they manage the view’s lifecycle and performance implications.</p><p><strong>a. removeView(view)</strong> → The view is physically removed from the view hierarchy. The layout system completely forgets about it, and you must re-add it to display it again.</p><p><strong>b. view.setVisibility(GONE)</strong> → The view remains in memory but is excluded from measurement and drawing passes. It can be quickly restored by toggling its visibility back to VISIBLE or INVISIBLE.</p><h4>Cut the crap, just tell me what to use when?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntpdmSJqEXEXP_WuEdyRPg.png" /></figure><h3>Best Practices for Efficient View Visibility Toggling</h3><p>Mastering view visibility management can significantly improve your app’s performance and user experience. Here are the key strategies to toggle views efficiently.</p><h4>1. Prefer GONE or INVISIBLE for Temporary State Changes</h4><p>When views need to be shown and hidden frequently, use visibility states rather than removing and re-adding views to the hierarchy.</p><h4>2. Avoid Layout Thrashing</h4><p>Repeated setVisibility() calls can trigger unnecessary layout passes. Always check the current state before changing visibility:</p><pre>if (view.visibility != View.GONE) {<br>    view.visibility = View.GONE<br>}</pre><h4>3. Use ViewStub or Manual Inflation for Heavier Views</h4><p>For optional or infrequently used views, don’t just hide them, but delay their creation entirely. This reduces initial layout complexity and memory usage.</p><h4>4. Consider Animations That Don’t Change Layout</h4><p>Not all animations are created equal. Some are lightweight and don’t require layout recalculation, while others force the system to re-measure and re-layout everything, causing performance issues.</p><p>Example scenario:</p><pre>Button(&quot;ClickMe&quot;)<br>TextView(&quot;Hello&quot;)</pre><p>Now, say you want to hide the button.</p><p><strong>Option 1: Using View.GONE</strong></p><pre>button.visibility = View.GONE</pre><p>This approach:</p><ul><li>Triggers a layout pass</li><li>Causes the TextView to move up</li><li>Forces the system to recalculate the entire layout</li></ul><p><strong>Option 2: Animation-Only Approach</strong></p><pre>button.animate().alpha(0f).start()</pre><p>Now, this approach:</p><ul><li>Fades the button out smoothly</li><li>Button <strong>still occupies its original space</strong>, mind it</li><li>No layout change, thus meaning no layout invalidation</li></ul><p>Result: Fast and smooth performance.</p><blockquote><strong>Key Takeaway:</strong></blockquote><blockquote>Some properties that trigger layout recalculation: visibility, margin, height, width</blockquote><blockquote>Some properties that don’t trigger layout recalculation: alpha, scaleX/Y, translationX/Y, rotation</blockquote><blockquote>Use animation properties wherever they fit your use case for better performance.</blockquote><h3>Don’t leave me hanging, tell me how to animate and free up space like View.GONE so that I get the best of both worlds?</h3><p>Want smooth animations with the space-saving benefits of View.GONE? You can achieve both by combining animation properties with visibility changes strategically timed using callback methods.</p><p>Hiding the view with animation:</p><pre>myView.animate()<br>    .alpha(0f)<br>    .translationY(-myView.height.toFloat())<br>    .setDuration(300)<br>    .withEndAction {<br>        // Remove view&#39;s space after animation ends<br>        myView.visibility = View.GONE<br>        <br>        //Reset for the next time<br>        myView.alpha = 1f<br>        myView.translationY = 0f<br>    }<br>    .start()</pre><p>Now, lets bring it back:</p><pre>//Reserve layout space<br>myView.visibility = View.INVISIBLE<br>myView.alpha = 0f<br>myView.translationY = -myView.height.toFloat()<br><br>myView.animate()<br>    .alpha(1f)<br>    .translationY(0f)<br>    .setDuration(300)<br>    .withStartAction {<br>        myView.visibility = View.VISIBLE<br>    }<br>    .start()</pre><p>This technique gives you smooth animations while properly managing layout space, combining performance with polish.</p><h3>ClipChildren and ClipToPadding: Controlling Drawing Boundaries</h3><p>Understanding clipChildren and clipToPadding is essential when creating custom animations, edge-to-edge layouts, or views that need to break traditional boundaries.​</p><h3>clipChildren</h3><p>Controls whether a parent ViewGroup allows its children to draw outside its own bounds.​ By default, its set to true</p><p>Flag behavior:</p><ul><li>true → Children <strong>cannot</strong> draw outside the parent&#39;s boundaries</li><li>false → Children <strong>can</strong> draw outside the parent&#39;s bounds​</li></ul><h4>When to Use clipChildren = false</h4><p><strong>1. Animating Views Beyond Container Bounds</strong><br>When you’re scaling, translating, or rotating views that temporarily extend beyond their parent during animation, setting clipChildren = false prevents visual clipping.​</p><p><strong>2. Custom Reveal Effects and Carousels</strong><br>For parallax effects, carousel sliders, or ViewPager2 implementations where adjacent items need to be partially visible, disabling clipping allows seamless visual flow.​</p><p><strong>3. Floating or Pop-Out Elements</strong><br>For cards with shadows, elevation effects, or elements that “pop out” of their containers, clipChildren = false ensures these visual enhancements aren&#39;t cut off.​</p><h3>clipToPadding</h3><p>Controls whether a ViewGroup clips its children to within its padding area. By default, its set to true</p><p>Flag behavior:</p><ul><li>true → Children <strong>are</strong> clipped and cannot draw inside the parent&#39;s padding area</li><li>false → Children <strong>are not</strong> clipped and can draw within the padding area​</li></ul><h4>When to Use clipToPadding = false</h4><p><strong>1. Scrollable Lists with Padding</strong><br>In RecyclerView or ScrollView, when you want items to scroll underneath toolbars or navigation bars smoothly rather than stopping at the padding boundary.​​</p><p>Example: A list with top/bottom padding where items should scroll under the padding instead of stopping before it, creating a more polished look.​</p><p><strong>2. Edge-to-Edge Layouts</strong><br>When implementing modern edge-to-edge designs where content extends behind system bars while maintaining safe spacing through padding.​</p><p><strong>3. Parallax Headers and Sticky Elements</strong><br>For smooth visual effects where content needs to slide behind or overlap padding areas, such as collapsing toolbars or floating action buttons.​</p><blockquote><strong>Important performance note: </strong>Don’t overuse these attributes as they can cause GPU overdraw and layout issues if applied carelessly. Always test thoroughly, especially with complex view hierarchies, and use them only when the design genuinely requires breaking default clipping behavior.</blockquote><h3><strong>Conclusion</strong></h3><p>Mastering these topics and the view optimization techniques can dramatically improve your app’s performance and user experience. From shared RecycledViewPools reducing memory overhead in nested lists, to strategic visibility management preventing unnecessary layout passes, each optimization compounds to create smoother, more responsive applications.</p><p>The key takeaway? Always profile before optimizing. Use Android Studio’s <strong>Layout Inspector</strong> and <strong>Profiler</strong> to identify actual bottlenecks in your view hierarchy. <strong><em>Not every screen needs a shared pool, and not every animation benefits from clipChildren adjustments.</em></strong></p><p>I initially planned to include ConstraintLayout’s internal working here, but the content was getting quite lengthy. I’ll be covering ConstraintLayout internals in a separate dedicated article outside this series.</p><p>💬 What’s your experience with these techniques? Share your experiences with RecyclerView pooling or lazy inflation! How much difference did it make in your apps? Share your optimization wins and challenges in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4957037f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Views, Layouts & Optimizations (2)]]></title>
            <link>https://medium.com/@rajabhandari100/views-layouts-optimizations-14a73621504f?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a73621504f</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-xml]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui-performance]]></category>
            <category><![CDATA[ui-optimization]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 18:43:46 GMT</pubDate>
            <atom:updated>2025-10-14T09:53:24.369Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Secret Life of Android Views: Performance Fundamentals &amp; Layout Optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xt1UPhVdeaC7zumkH1FbTA.png" /></figure><p>In <a href="https://medium.com/@rajabhandari100/views-layouts-optimizations-3aea727ff2cd">Part 1</a> of this blog series, we explored how Views and ViewGroups work under the hood: from creation and attachment to measurement, layout, and drawing.</p><p>Now, let’s go a layer deeper in the <strong>Part 2 of this blog series</strong>. It is time to understand why some layouts make your app feel buttery smooth while others turn it into a slideshow.</p><p>In this part, we will cover:</p><ul><li>How view hierarchy depth impacts performance</li><li>Layout inflation strategies and AsyncLayoutInflater</li><li>Flattening techniques with practical examples</li><li>Using ViewStub, &lt;merge&gt;, and &lt;include&gt; for smarter layouts</li></ul><h3>How Hierarchy Depth Affects Performance</h3><p>Remember the measure → layout → draw cycle from the first blog? It becomes a bottleneck when your View hierarchy resembles a Russian nesting doll.</p><p>When we drag a few LinearLayouts and RelativeLayouts into your XML, it’s easy to underestimate the cost of deeply nested hierarchies. But Android’s rendering pipeline traverses your entire tree multiple times per frame, and <strong>the deeper the tree, the more expensive this traversal becomes.</strong></p><h4>1. Repeated Traversals</h4><p>Every time the system measures, lays out, or draws, it walks down your entire View tree.</p><p>A deeper hierarchy = more nodes to visit = more CPU time. Simple math.</p><pre>&lt;!-- Unnecessarily deep hierarchy --&gt;<br>&lt;LinearLayout&gt;           &lt;!-- Level 1 --&gt;<br>  &lt;LinearLayout&gt;         &lt;!-- Level 2 --&gt;<br>    &lt;LinearLayout&gt;       &lt;!-- Level 3 --&gt;<br>      &lt;TextView /&gt;       &lt;!-- Level 4 --&gt;<br>    &lt;/LinearLayout&gt;<br>  &lt;/LinearLayout&gt;<br>&lt;/LinearLayout&gt;</pre><h4>2. Multiple Measure/Layout Passes</h4><p>Some ViewGroups <strong>require two or more measurement passes </strong>to determine final positions:</p><ul><li><strong>RelativeLayout →</strong> first pass estimates relationships, second pass finalizes positions.</li><li><strong>LinearLayout with weights →</strong> measures once then again to distribute weights.</li><li><strong>GridLayout with gravity →</strong> multiple passes for complex positioning.</li></ul><p>And, again when you nest these, the <strong>passes compound</strong>.</p><blockquote>A 3-level nested RelativeLayout can trigger many measurement passes for a single update!</blockquote><h4>3. Memory and Rendering Overhead</h4><p>Each View object comes with <strong>memory cost</strong>. It also adds:</p><ul><li>Allocation time during inflation</li><li>GC pressure from frequent object creation and destruction</li><li>Rendering overhead, especially in RecyclerView where Views are constantly recycled</li></ul><h4>4. Overdraw Amplification by Complex layouts</h4><p>Overdraw happens when the same pixel is drawn multiple times per frame.<br>More overlapping views(even when invisible!) can cause overdraw, where the same pixels gets drawn multiple times. This burdens the GPU and reduces frame rendering efficiency.</p><p>For example:</p><pre>&lt;RelativeLayout<br>    android:background=&quot;@android:color/white&quot;&gt;  &lt;!-- Only needed here --&gt;<br>    &lt;LinearLayout<br>     android:background=&quot;@android:color/white&quot;&gt;  &lt;!-- Redundant --&gt;<br>        &lt;TextView<br>         android:background=&quot;@android:color/white&quot;   &lt;!-- Redundant --&gt;<br>         ... /&gt;<br>    &lt;/LinearLayout&gt;<br>&lt;/RelativeLayout&gt;</pre><p>All 3 Views paint the same white background. The GPU ends up doing redundant work painting the same pixels three times.</p><p>Another classic case:</p><pre>&lt;FrameLayout&gt;<br>    &lt;CardView ... /&gt;  &lt;!-- Card 1 --&gt;<br>    &lt;CardView ... /&gt;  &lt;!-- Card 2 --&gt;<br>    &lt;CardView ... /&gt;  &lt;!-- Card 3 (on top) --&gt;<br>&lt;/FrameLayout&gt;</pre><p>Even though Card 3 covers everything, the GPU still draws Card 1 and Card 2 underneath. This unnecessary work can eat into your frame budget quickly.</p><h3>Layout Inflation Explained</h3><p>‘Inflating’ a layout means converting an XML layout file into actual View objects in memory.</p><p>It happens in two ways:</p><ol><li><strong>XML Inflation<br></strong>Using LayoutInflater.inflate() or implicitly through setContentView() in an Activity. Internally, Android:</li></ol><ul><li>Reads the XML file</li><li>Uses reflection to call the View’s constructor with AttributeSet</li><li>Applies <strong>XML attributes as View properties</strong></li></ul><p><strong>2. Programmatic Creation</strong><br> Creating Views manually with new View(context).<br> Slightly faster since there’s no XML parsing or reflection.</p><pre>// XML inflation (standard)<br>val view = LayoutInflater.from(context)<br>    .inflate(R.layout.my_layout, parent, false)<br><br>// Programmatic creation (may avoid some reflection cost)<br>val linearLayout = LinearLayout(context).apply {<br>    orientation = LinearLayout.VERTICAL<br>    addView(TextView(context).apply { text = &quot;Dynamic Text&quot; })<br>}</pre><blockquote>Programmatic creation can avoid some reflection overhead and may be faster in certain scenarios, but XML is more maintainable. So, measure before optimizing.</blockquote><h3>AsyncLayoutInflater</h3><p>AsyncLayoutInflater (available in AndroidX and supported on API 21+) lets you inflate layouts <strong>on a background thread</strong>. This can help <strong>reduce startup latency</strong> and <strong>avoid UI jank</strong> when dealing with heavy or complex layouts.</p><p><strong>How it works:</strong></p><ol><li>You call AsyncLayoutInflater.inflate(layoutResId, parent, callback) from the main thread.</li><li>Internally, the <strong>XML layout is inflated on a background thread</strong>.</li><li>Once inflation is done, the onInflateFinishedListener callback is invoked <strong>on the main thread</strong> with the inflated View.</li><li>You can then attach this view to the parent and perform any initialization.</li></ol><pre>AsyncLayoutInflater(this).inflate(<br>    R.layout.complex_layout,<br>    parentViewGroup<br>) { view, _, parent -&gt;<br>    //----- Main thread ----<br>    parent?.addView(view)<br>    <br>    //Initialize view bindings or listeners here<br>    setupViewBindings(view)<br>}</pre><blockquote>Use cases: complex screens with many views, heavy RecyclerView items, or sluggish startup screens.</blockquote><h3>Flattening Layouts</h3><p>‘Flattening’ means reducing the <strong>depth</strong> and <strong>complexity</strong> of your View hierarchy by:</p><ul><li>Eliminating unnecessary ViewGroups</li><li>Using optimized layouts like ConstraintLayout</li><li>Merging nested containers or removing redundant wrappers</li></ul><p>But, why flatten?</p><ul><li>Faster layout traversal</li><li>Less overdraw</li><li>Lower memory usage</li><li>Smoother rendering</li></ul><p><strong>Before (not flattened): Using nested LinearLayouts</strong></p><pre>&lt;LinearLayout android:orientation=&quot;vertical&quot;&gt;<br>    &lt;LinearLayout android:orientation=&quot;horizontal&quot;&gt;<br>        &lt;ImageView android:id=&quot;@+id/avatar&quot;/&gt;<br>        &lt;TextView android:id=&quot;@+id/username&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br>    &lt;Button android:id=&quot;@+id/follow_button&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><p>Two nested LinearLayouts just to position an image, text, and a button.</p><p><strong>After (flattened): Using single ConstraintLayout</strong></p><pre>&lt;ConstraintLayout&gt;<br>    &lt;ImageView android:id=&quot;@+id/avatar&quot; .../&gt;<br>    &lt;TextView android:id=&quot;@+id/username&quot; .../&gt;<br>    &lt;Button android:id=&quot;@+id/follow_button&quot; .../&gt;<br>&lt;/ConstraintLayout&gt;</pre><p>Same visual result, but using <strong>one ViewGroup instead of two</strong>.<br>Result? fewer measure/layout passes.</p><h3>Smart Layout Tools: ViewStub, &lt;merge&gt;, and &lt;include&gt;</h3><h4>1. ViewStub</h4><p>ViewStub is a lightweight, tiny placeholder View that we define in XML but doesn’t inflate its contents until you explicitly tell it to. It only inflates its contents when you call inflate() and the stub is replaced by the inflated layout.</p><h4>Why use it?</h4><ul><li>It saves memory and CPU by deferring inflation.</li><li>Ideal for optional layouts like loading, spinners, error messages, empty states, ads or infrequent screens</li></ul><pre>&lt;ViewStub<br>    android:id=&quot;@+id/error_stub&quot; //Id of ViewStub<br>    android:inflatedId=&quot;@+id/error_content&quot; // This will be the id of the layout after inflation<br>    android:layout=&quot;@layout/error_view&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;/&gt;</pre><pre>&lt;!-- error_view.xml --&gt;<br><br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/actual_root&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/error_message&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><pre>val stub = findViewById&lt;ViewStub&gt;(R.id.error_stub)<br>val errorView = stub.inflate()<br><br>// You can access the inflated content using the returned view<br>errorView.findViewById&lt;TextView&gt;(R.id.error_message).text = message<br><br>//Alternatively, access via inflatedId after inflation like this<br>val inflatedContainer = findViewById&lt;LinearLayout&gt;(R.id.error_content)<br>inflatedContainer?.findViewById&lt;TextView&gt;(R.id.error_message)?.text = message<br><br>// This will be wrong. ViewStub no longer exists after inflation<br>// val stubAgain = findViewById&lt;ViewStub&gt;(R.id.error_stub) // This will return null</pre><blockquote>Note: After inflation, the ViewStub is permanently replaced by the inflated layout in the View hierarchy.</blockquote><h4>2. &lt;merge&gt;</h4><p>&lt;merge&gt; is a special XML tag that doesn’t create a ViewGroup, but lets child views be inserted directly into the parent’s hierarchy.</p><h4>Why use it?</h4><ul><li>Helps flatten layouts when using &lt;include&gt;</li><li>Avoids unnecessary ViewGroup inflation, thus flattening the final View hierarchy.</li></ul><h4>3. &lt;include&gt;</h4><p>&lt;include&gt; is a way to embed one XML layout into another layout. It keeps layout files DRY and reusable.</p><h4>Why use it?</h4><ul><li>Keeps large layouts manageable.</li><li>Helps break UIs into modular parts like headers, footers or common rows.</li><li>Used with or without &lt;merge&gt; depending on structure.</li></ul><blockquote><strong>IMPORTANT:</strong> Don’t think that &lt;include&gt; improves performance anywhere. No, it doesn’t. It’s just to make views modular. <br>When we use &lt;merge&gt; alongside &lt;include&gt;, and if using &lt;merge&gt; reduces the number of ViewGroups, only then do we see some improvement in performance. Otherwise, there’s no performance benefit.</blockquote><h3>Techniques for Flattening Layouts</h3><h4>1. Use ConstraintLayout Instead of Nested LinearLayouts</h4><p>Nested LinearLayouts are one of the most common sources of deep hierarchies. ConstraintLayout allows you to position multiple Views relative to each other and the parent in a single container, eliminating multiple nesting levels.</p><p><strong>Before: Nested LinearLayouts</strong></p><pre>&lt;LinearLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/avatar&quot;<br>            android:layout_width=&quot;40dp&quot;<br>            android:layout_height=&quot;40dp&quot;/&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/username&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;User Name&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/follow_button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Follow&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><p><strong>After: Single ConstraintLayout</strong></p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/avatar&quot;<br>        android:layout_width=&quot;40dp&quot;<br>        android:layout_height=&quot;40dp&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;/&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/username&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintTop_toTopOf=&quot;@id/avatar&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@id/avatar&quot;<br>        android:text=&quot;User Name&quot;/&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/follow_button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/avatar&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        android:text=&quot;Follow&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>We see:<br> 1. Same visual result.<br> 2. Fewer ViewGroups.<br> 3. Better performance during measurement and layout.</p><h4>2. Use &lt;merge&gt; Tag for Included Layouts</h4><p>When using &lt;include&gt;, developers often wrap child layouts in a container unnecessarily, creating extra hierarchy levels. <br>For example:</p><h4>Before: Nested LinearLayouts</h4><pre>&lt;!-- parent_layout.xml --&gt;<br><br>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;include layout=&quot;@layout/child_layout&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><pre>&lt;!-- child_layout.xml --&gt;<br><br>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;horizontal&quot;&gt;<br><br>    &lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Content&quot;/&gt;<br><br>    &lt;Button<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Action&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><p>Here, the included layout introduces <strong>an extra LinearLayout</strong> unnecessarily. You end up with two nested LinearLayouts (parent + child).</p><h4>After: Using &lt;merge&gt;</h4><pre>&lt;!-- child_layout.xml --&gt;<br><br>&lt;merge xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Content&quot;/&gt;<br><br>    &lt;Button<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Action&quot;/&gt;<br>&lt;/merge&gt;</pre><p>With &lt;merge&gt;, the included views are added directly to the parent’s hierarchy without an extra wrapper. This is a simple and very effective flattening trick.</p><blockquote>Note: &lt;merge&gt; doesn’t create a new ViewGroup. It simply inserts its children directly into the parent.</blockquote><h4>3. Use ViewStub for Lazy Inflation</h4><p>ViewStub is a lightweight, invisible placeholder that you can inflate on demand.</p><h4>4. Remove Redundant Wrappers</h4><p>It’s surprisingly common to see unnecessary wrappers like:</p><ul><li>FrameLayout around a single child</li><li>LinearLayout used only for padding or spacing</li></ul><p>Every wrapper costs memory and traversal time, so reduce/remove them wherever possible.</p><h3>Bonus info: Detecting and Fixing Overdraw</h3><p>Open <strong>Developer Options</strong> and enable <strong>Show GPU Overdraw, </strong>and then open your app<strong> </strong>to visualize problematic areas:</p><ul><li>True color = no overdraw</li><li>Blue = 1x overdraw</li><li>Green = 2x overdraw</li><li>Pink = 3x overdraw</li><li>Red = 4x or more → fix immediately</li></ul><h3>Conclusion</h3><p>Performance optimization is about trade-offs you know. A slightly deeper hierarchy might be worth it for clarity or reuse. The important part is knowing the cost and measuring before you act.</p><p>You now have a checklist of practical steps to reduce expensive layout work: flatten hierarchies, use &lt;merge&gt; where it helps, defer optional content with ViewStub or AsyncLayoutInflater when appropriate, and keep an eye on overdraw.</p><p>In Part 3 we will cover advanced topics and optimizations: RecyclerView pooling strategies, deeper overdraw elimination, ConstraintLayout internals, and view visibility and advanced view toggling patterns. Stay tuned guys!</p><p>💬 Also, I would love to hear your thoughts and techniques. Share your experiences in the comments to keep the conversation going.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a73621504f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Views, Layouts & Optimizations]]></title>
            <link>https://medium.com/@rajabhandari100/views-layouts-optimizations-3aea727ff2cd?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aea727ff2cd</guid>
            <category><![CDATA[android-views]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[custom-views]]></category>
            <category><![CDATA[ui-performance]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 10:27:54 GMT</pubDate>
            <atom:updated>2025-10-10T18:45:58.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Views, Layouts &amp; Optimizations (1)</h3><h4>The Secret Life of Android Views: Foundations &amp; Lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QpetjIavDyXYvzPzhW6Zw.png" /></figure><p>If you’ve spent any time building Android UIs, you’ve probably dragged a few TextViews and Buttons onto a layout, hit “Run,” and moved on with life (no worries, I’ve done the same!). But beneath that humble XML lies a surprisingly elegant system that powers everything from the simplest button to the most complex nested layouts.</p><p>Now, I know.. I know what you might be thinking: <em>“Wait, isn’t Compose the new way to build UIs?”</em> Absolutely. Compose is the shiny new kid on the block, and it’s fantastic. But here’s the catch: most production apps still rely heavily on the <strong>traditional View system</strong>, either entirely or in hybrid setups. And even if you’re going full Compose, understanding how Views and Layouts work is like knowing the engine under your car’s hood. Atleast it will make you a better driver. Right?</p><p>This is the <strong>first part of a multi-part series</strong> where we’ll peel back the curtain on the View system and then layer on optimization techniques in later parts. We’ll move from fundamental concepts to deeper internals and finally to practical performance strategies. By the end, those “mysterious performance issues” that haunt complex screens will start making a lot more sense.</p><p>In this part, we’ll look at:</p><ul><li>What View and ViewGroup really are</li><li>Why ViewGroup inherits from View (spoiler: it’s a clever design pattern)</li><li>How a View’s lifecycle works from creation to drawing</li><li>What methods like invalidate() and requestLayout() actually do</li></ul><p>Let’s start with the basics.</p><h3>View and ViewGroup</h3><p>Lets state the obvious, in Android, <strong>everything you see on screen starts with a View</strong>.<br>A View is the basic UI Component in Android.</p><ul><li>It represents a single rectangular element on the screen. (Button, TextView etc.)</li><li>It knows how to draw itself, and can handle touch events and user interaction.</li><li>It is the root class of all UI widgets in Android.</li></ul><p>Now, enters the ViewGroup.<br>A ViewGroup is also a View… but with a twist. It can <strong>hold other Views</strong> inside it.<br>We should also know that ViewGroup inherits from View.<br>So, we can say, that a ViewGroup is a special type of View that,</p><ul><li>Acts as an invisible container for other <strong>Views</strong> and <strong>ViewGroups</strong>!</li><li>It is the base class for all layout container such as LinearLayout, FrameLayout etc.</li><li>It defines how its children are measured and arranged on screen.</li></ul><h4>But, you would wonder why ViewGroup inherits from View?</h4><p>ViewGroup inherits from View to implement the <strong>Composite design pattern</strong>, enabling uniform treatment during Android’s rendering pipeline.</p><p>The actual beauty lies in <strong>uniformity</strong>: <em>both containers and leaf views can participate identically in the measure-layout-draw lifecycle.</em> This allows the Android framework to treat a single TextView and a complex LinearLayout uniformly: both are just “Views” that can measure(), layout(), and draw() themselves. Cool, isnt it?</p><p>The inheritance provides the rendering capabilities, while composition adds container functionality like managing child views. This design enables <strong>recursive traversal</strong> where every node in the view tree follows the same interface, making the UI system elegant and efficient.</p><pre>// Both treated uniformly by the framework<br>val textView: View = TextView(context)<br>val container: View = LinearLayout(context)<br>// Same rendering methods (measure(), layout(), and draw()) available on both</pre><p>This pattern allows Android to build complex UI hierarchies while maintaining a simple, consistent API for the rendering system.</p><h3>Android View Lifecycle</h3><p>Every View in Android goes through a well-defined <strong>lifecycle</strong>: it’s <strong>created</strong>, <strong>attached</strong> to a window, then <strong>measured</strong>, <strong>laid out</strong>, and finally <strong>drawn</strong> on the screen. When a View’s state changes, methods like invalidate() and requestLayout() help trigger redraws or re-measurements.</p><h3>1. Creation Phase</h3><p>Every View begins life either through XML inflation or programmatic creation.</p><ul><li><strong>Constructors:</strong> When a View is inflated or created, its constructor runs. Android chooses which constructor to call <em>based on context and attributes.</em></li><li><strong>onFinishInflate():</strong> Once all child views are inflated from XML, this callback fires. <br><em>This is a perfect place for doing view lookups, initializing child references, or some basic setup. Think of it as “the View just moved into its new house and is now unpacking boxes.”</em></li></ul><h3>2. Attachment &amp; Detachment</h3><p>Once created, a View gets attached to a window.</p><ul><li><strong>onAttachedToWindow():</strong> Called when the View is actually attached to the active window. <br><em>Great place for starting animations, setting listeners, or anything that depends on </em><strong><em>being on screen</em></strong><em>.</em></li><li><strong>onDetachedFromWindow():</strong> Its triggered when the View is removed or the window is destroyed. <br><em>Ideal for cleaning up listeners, stopping animations, or releasing resources to prevent memory leaks. Basically, clean up your mess before you leave the room.</em></li></ul><h3>3. Traversal: Measure → Layout → Draw</h3><p>This is where things get serious. The <strong>Measure</strong>, <strong>Layout</strong>, and <strong>Draw</strong> phases happen here, usually in that order.</p><p>The View hierarchy is like a tree you know, the parent ViewGroup starts at the root and traverses down to the leaf Views. Each phase trickles down the hierarchy.</p><blockquote><em>Note: The Measure and Layout phases always happen together, sequentially, before drawing.</em></blockquote><h4>a. onMeasure(int widthMeasureSpec, int heightMeasureSpec)</h4><p>Each View calculates how big it wants to be.<br>For a ViewGroup, it will call onMeasure() on each of its children, then decide its own size based on their measurements.</p><ul><li>You don’t return values here. Instead, you call setMeasuredDimension(width, height) to store the measured size (when overriding onMeasure() in custom Views or ViewGroups).</li></ul><pre>override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {<br>    // Custom measurement logic here<br>    setMeasuredDimension(calculatedWidth, calculatedHeight)<br>}</pre><p>Each MeasureSpec is a combination of a <strong>mode</strong> and a <strong>size</strong>, passed from parent to child.</p><p>The modes are:</p><ol><li><strong>EXACTLY</strong> — The parent has determined an exact size for the child.</li><li><strong>AT_MOST</strong> — The child can be as big as it wants up to a maximum size.</li><li><strong>UNSPECIFIED</strong> — The parent doesn’t impose any constraint. The child can be whatever it wants.</li></ol><h4>b. onLayout(boolean changed, int left, int top, int right, int bottom)</h4><p>Once measurement is done, it’s time to place Views on the screen.<br>This method positions each View within its parent by setting their bounds.</p><p>Custom ViewGroups must override this to arrange their children manually. Think of this as arranging furniture in a room after measuring the space.</p><h4>c. onDraw(Canvas canvas)</h4><p>Finally, Views show themselves on screen. This method is where the actual drawing happens, using the Canvas object.</p><blockquote>⚠️ <strong>Important:</strong> Don’t allocate new objects here in onDraw(). onDraw() can run many times per second, and allocations here are basically open invitations for the Garbage Collector.</blockquote><h3>4. State Changes and Redrawing</h3><p>Views don’t sit still. Their size or appearance may change due to user interaction or data updates. That’s where these methods come in:</p><ul><li><strong>invalidate()</strong> tells the system: “I’ve changed visually. Please redraw me.” It only triggers the <strong>Draw</strong> phase.</li><li><strong>requestLayout()</strong> says: “My size or position changed. Let’s re-measure and lay out again.”, so it needs to go through <strong>Measure and Layout</strong> again (and eventually Draw too).<br><em>Use this when you’ve changed something that affects positioning or size.</em></li></ul><h3>Conclusion</h3><p>Understanding the View lifecycle is like learning the choreography of a dance. Once you’ve got the rhythm, your Views glide smoothly across the screen. Miss a beat, and you will find yourself debugging at 2 AM wondering why onDraw() ghosted you.</p><p>These fundamentals are the backbone of everything that happens in the rendering pipeline. Whether you’re creating a simple custom View or debugging a complex nested layout, knowing how Views are created, measured, laid out, and drawn gives you the superpower to reason about what’s happening on screen.</p><p>In the next part of this series, we’ll build on this knowledge and explore <strong>how View hierarchies impact performance</strong>, why some layouts are slower than others, and practical techniques to keep your UI fast and efficient. Stay tuned guys! Things will get interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aea727ff2cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveData From Scratch: Building Your Own Lifecycle-Aware Observable]]></title>
            <link>https://medium.com/@rajabhandari100/livedata-from-scratch-building-your-own-lifecycle-aware-observable-019f8e40e3a7?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/019f8e40e3a7</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 12:14:58 GMT</pubDate>
            <atom:updated>2025-10-01T12:14:58.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQ2GQfoXCtaIgrbyQSsbHQ.png" /></figure><p>Remember when we tore apart LiveData’s internals in the <a href="https://medium.com/@rajabhandari100/deconstructing-livedata-understanding-the-internal-mechanics-41263f8a2a0e"><strong>last post</strong></a>? We peeked into things like mData, mVersion, and how observers are wrapped and managed. All the lifecycle-aware magic under the hood suddenly made sense. But theory only takes you so far. At some point, you’ve got to roll up your sleeves and build the thing yourself.</p><p>That’s what we’re doing today. Instead of just nodding along when someone says <em>“LiveData is lifecycle-aware”</em>, we’re going to recreate it from scratch.</p><blockquote>Think of this as “<em>LiveData: The First Draft</em>”; just all the learning, none of the production-ready guarantees.</blockquote><p>The best way to really understand something is to build it yourself. And once you know how it works inside out, you’ll be sharper when working with LiveData, Flow, or whatever reactive tool comes next.</p><h3>Implementing LiveData from Scratch</h3><blockquote>Let’s imagine we want to create our own version of LiveData. Take a breath, and think: <strong>What do we need?</strong></blockquote><h4>1. We need to hold some data</h4><p>At its core, LiveData is just a container for data. It needs to hold a value and let us read it later. Let’s start simple:</p><pre>class MyLiveData&lt;T&gt; {<br>    private var dataHolder: T? = null<br><br>    fun getValue(): T? = dataHolder<br>}</pre><p>Nothing fancy yet. We can store a value and retrieve it, like a glorified variable with a getter.</p><h4>2. We need to update the data</h4><p>LiveData gives us two ways to push new values:</p><ul><li>setValue() for synchronous updates (on the main thread)</li><li>postValue() for async updates (handy when you’re off the main thread)</li></ul><p>Let’s add both:</p><pre>private val mainHandler = Handler(Looper.getMainLooper())<br><br>// Synchronous update<br>fun setValue(value: T) {<br>    dataHolder = value<br>    notifyObservers()<br>}<br><br>// Asynchronous update<br>fun postValue(value: T) {<br>    mainHandler.post { setValue(value) }<br>}</pre><p>With this, our LiveData can update instantly or schedule updates safely back on the main thread.</p><h4>3. We need observers</h4><p>A container without observers is pretty boring. <strong>Observers</strong> are what make LiveData reactive. Whenever the data changes, these callbacks should be triggered.</p><p>But there’s a catch: <strong>LiveData doesn’t just spam observers all the time</strong>. It’s lifecycle-aware. If your screen isn’t visible, LiveData won’t bother sending updates. That means we need a way to:</p><ol><li>Wrap each observer.</li><li>Track the lifecycle of the LifecycleOwner subscribing.</li></ol><p>That’s why we use:</p><ul><li><strong>MyObserverWrapper</strong>→ stores the observer.</li><li><strong>LifecycleObserverWrapper</strong>→ listens to the owner’s lifecycle.</li></ul><pre>// Write this typealias outside the class<br>typealias MyObserver&lt;T&gt; = (T?) -&gt; Unit  <br><br>private val observers = HashMap&lt;MyObserverWrapper, LifeCycleObserverWrapper&gt;()<br><br>// Wrapper around MyObserver, helps keep things clean and focused<br>private inner class MyObserverWrapper(val observer: MyObserver&lt;T&gt;) {<br>    fun notify(value: T?) {<br>        observer(value)<br>    }<br>}<br><br>private inner class LifeCycleObserverWrapper(<br>    val lifecycleOwner: LifecycleOwner,<br>    private val wrapper: MyObserverWrapper<br>) : DefaultLifecycleObserver {<br><br>    override fun onStart(owner: LifecycleOwner) {<br>        // When screen comes to foreground, deliver latest value<br>        wrapper.notify(dataHolder)<br>    }<br><br>    override fun onDestroy(owner: LifecycleOwner) {<br>        // Auto remove to prevent leaks<br>        removeObserver(wrapper.observer)<br>    }<br>}</pre><h4>4. Adding and removing observers</h4><p>Now we provide public APIs to attach and detach observers:</p><pre>fun addObserver(lifecycleOwner: LifecycleOwner, observer: MyObserver&lt;T&gt;) {<br>    val wrapper = MyObserverWrapper(observer)<br>    val lifecycleObserver = LifeCycleObserverWrapper(lifecycleOwner, wrapper)<br><br>    lifecycleOwner.lifecycle.addObserver(lifecycleObserver)<br>    observers[wrapper] = lifecycleObserver<br><br>    // If already started, deliver the current value immediately<br>    if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {<br>        wrapper.notify(dataHolder)<br>    }<br>}<br><br>fun removeObserver(observer: MyObserver&lt;T&gt;) {<br>    val wrapper = observers.keys.find { it.observer === observer }<br>    wrapper?.let {<br>        observers[it]?.let { lifeCycleObserver -&gt;<br>            lifeCycleObserver.lifecycleOwner.lifecycle.removeObserver(lifeCycleObserver)<br>        }<br>        observers.remove(it)<br>    }<br>}</pre><p>This feels familiar, right? Just like the real LiveData.observe() and removeObserver().</p><h4>5. Notifying all observers</h4><p>Finally, whenever a new value comes in, we loop through all active observers and notify them:</p><pre>private fun notifyObservers() {<br>    observers.keys.forEach { wrapper -&gt;<br>        val lifecycle = observers[wrapper]?.lifecycleOwner?.lifecycle<br>        if (lifecycle != null &amp;&amp; lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {<br>            wrapper.notify(dataHolder)<br>        }<br>    }<br>}</pre><h3>🎉 Final Code</h3><p>Putting it all together, here’s our custom <strong>MyLiveData</strong>:</p><pre>typealias MyObserver&lt;T&gt; = (T?) -&gt; Unit<br><br>open class MyLiveData&lt;T&gt; {<br><br>    private var dataHolder: T? = null<br>    private val observers = HashMap&lt;MyObserverWrapper, LifeCycleObserverWrapper&gt;()<br>    private val mainHandler = Handler(Looper.getMainLooper())<br><br>    //Synchronous setValue<br>    protected open fun setValue(value: T) {<br>        dataHolder = value<br>        notifyObservers()<br>    }<br><br>    //Asynchronous postValue<br>    protected open fun postValue(value: T) {<br>        mainHandler.post { setValue(value) }<br>    }<br><br>    fun getValue(): T? = dataHolder<br><br>    fun addObserver(lifecycleOwner: LifecycleOwner, observer: MyObserver&lt;T&gt;) {<br>        val wrapperAroundObserver = MyObserverWrapper(observer)<br>        val lifecycleObserverWrapper = LifeCycleObserverWrapper(lifecycleOwner, wrapperAroundObserver)<br>        lifecycleOwner.lifecycle.addObserver(lifecycleObserverWrapper)<br>        observers[wrapperAroundObserver] = lifecycleObserverWrapper<br><br>        // Notify immediately if lifecycle is at least started<br>        if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {<br>            wrapperAroundObserver.notify(dataHolder)<br>        }<br>    }<br><br>    fun removeObserver(observer: MyObserver&lt;T&gt;) {<br>        val wrapperAssociatedWithTheGivenObserver = observers.keys.find { it.observer === observer }<br>        wrapperAssociatedWithTheGivenObserver?.let {<br><br>            observers[it]?.let { lifeCycleObserver -&gt;<br>                lifeCycleObserver.lifecycleOwner.lifecycle.removeObserver(lifeCycleObserver)<br>            }<br><br>            observers.remove(it) //removing from the global map we have in this class<br>        }<br>    }<br><br>    private fun notifyObservers() {<br>        observers.keys.forEach { wrapper -&gt;<br>            val lifecycle = observers[wrapper]?.lifecycleOwner?.lifecycle<br>            if (lifecycle != null &amp;&amp; lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {<br>                wrapper.notify(dataHolder)<br>            }<br>        }<br>    }<br><br>    //Wrapper around MyObserver, helps keep things clean and focused<br>    private inner class MyObserverWrapper(val observer: MyObserver&lt;T&gt;) {<br>        fun notify(value: T?) {<br>            observer(value)<br>        }<br>    }<br><br>    private inner class LifeCycleObserverWrapper(<br>        val lifecycleOwner: LifecycleOwner,<br>        private val observerWrapper: MyObserverWrapper<br>    ) : DefaultLifecycleObserver {<br><br>        override fun onStart(owner: LifecycleOwner) {<br>            observerWrapper.notify(dataHolder)<br>        }<br><br>        override fun onDestroy(owner: LifecycleOwner) {<br>            removeObserver(observerWrapper.observer)<br>        }<br>    }<br>}</pre><h3>Intuition Recap</h3><ul><li><strong>Data Holder</strong> → stores the value</li><li><strong>setValue / postValue</strong> → update synchronously or asynchronously</li><li><strong>Observer Wrappers</strong> → hold observer callbacks and lifecycle owners</li><li><strong>Lifecycle Awareness</strong> → only notify if the lifecycle is <strong><em>at least STARTED</em></strong></li><li><strong>Auto-removal</strong> → prevent memory leaks by removing on onDestroy</li></ul><h3>Bonus: MutableLiveData</h3><p>For MutableLiveData, we just make setValue and postValue public so that the data becomes mutable for this class:</p><pre>class MyMutableLiveData&lt;T&gt; : MyLiveData&lt;T&gt;() {<br>    public override fun setValue(value: T) {<br>        super.setValue(value)<br>    }<br><br>    public override fun postValue(value: T) {<br>        super.postValue(value)<br>    }<br>}</pre><blockquote>Check out the usage examples for custom LiveData in my Github repository mentioned at the end of the blog.</blockquote><h3>Wrapping Up</h3><p>And that’s it. We just built our own LiveData from scratch. It isn’t as feature-packed as the official one (no versioning, no threading edge cases), but it gives an insight to the fundamentals: data storage, lifecycle awareness, observer management, and leak-free cleanup.</p><p>Next time you use LiveData in your app, you’ll know exactly what’s going on under the hood when you call setValue(). And the best part? You built it yourself. That’s the kind of understanding that sticks.</p><p>I’ve pushed the full code along with usage examples to GitHub. If you’re curious, go check it out, play with it, and feel free to suggest improvements or missing features.</p><p>👉 <a href="https://github.com/IamRaja007/CustomLiveData">Check out the project in GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=019f8e40e3a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deconstructing LiveData: Understanding the Internal Mechanics]]></title>
            <link>https://medium.com/@rajabhandari100/deconstructing-livedata-understanding-the-internal-mechanics-41263f8a2a0e?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/41263f8a2a0e</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[architecture-components]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 17:41:31 GMT</pubDate>
            <atom:updated>2025-09-29T17:41:31.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDhUa5zMrmS62lMbydsmfQ.png" /><figcaption>I call it (A)LiveData</figcaption></figure><p>Ever wondered what happens behind the scenes when you call setValue() on LiveData?</p><p>I know what you must be thinking: “Hey, we have Kotlin Flow these days! StateFlow and SharedFlow are the new kids on the block.” Well, let me validate your opinion: yes yes, you’re absolutely right. Flow is indeed becoming the preferred choice for modern Android development.</p><p>But LiveData isn’t going anywhere anytime soon. Millions of apps still rely on it, and understanding its internals will make you a better developer overall.</p><p>Today, we’re going to dissect LiveData like it’s a frog in biology class, except way more fun and significantly less smelly. We’ll explore how it stores data, manages observers, and handles those tricky re-entry scenarios.</p><h3>What is LiveData?</h3><p><strong>LiveData</strong> is a <strong>lifecycle-aware observable data holder class</strong> from Android’s Architecture Components. It lets us store and expose data in a way that UI components like Activity or Fragment can observe the changes made to the data.</p><p>Key features include:</p><ul><li>It <strong>notifies observers of data changes</strong> only when their associated LifecycleOwner is in an <strong>active state</strong> (STARTED or RESUMED).</li><li>It <strong>retains the latest value</strong>, so new observers immediately receive the most recent data upon becoming active.</li><li>It <strong>automatically cleans up observers</strong> when the associated lifecycle owner is destroyed, preventing memory leaks and wasted updates.</li></ul><blockquote>Think of LiveData as that responsible friend who only bothers you with updates when you’re actually available to handle them, and remembers to clean up after themselves when the party’s over.</blockquote><h3><strong>How LiveData holds data?</strong></h3><p>Inside LiveData&lt;T&gt; (from androidx.lifecycle.LiveData), data is managed through several key fields that work together like a well-orchestrated symphony:</p><ul><li><strong>mData</strong> → Holds the current value of type T.</li><li><strong>mVersion</strong> → An integer that starts at START_VERSION = -1. It is incremented every time setValue() is called.</li><li><strong>mPendingData</strong> → A temporary holder used by postValue() for background-safe updates.</li><li><strong>NOT_SET</strong> → A sentinel object representing “no value set yet.” It is used to initialize mData and mPendingData. <br>(Note: A <strong>sentinel object</strong> is a special, unique object used in programming to signal a particular condition, often the end of data input or the absence of a value)</li></ul><h4>Setting Values: The Tale of Two Methods</h4><p>Now, when you call <strong>setValue(T value)</strong> (on the main thread):</p><ul><li>mData is updated.</li><li>mVersion is incremented.</li><li>Observers are notified synchronously if they are active.</li></ul><p>And, when you call <strong>postValue(T value)</strong> from any thread (especifically from background threads):</p><ul><li>The value is stored in mPendingData.</li><li>A runnable is posted to the main thread via ArchTaskExecutor.</li><li>Once executed, the runnable calls setValue() with the pending value.</li></ul><blockquote>If multiple postValue() calls are made before the main thread processes the runnable, only the <strong>latest value</strong> is kept; older pending values are overwritten.</blockquote><h3><strong>How LiveData observes changes and notifies its observers?</strong></h3><p>LiveData manages observers and ensures they receive updates safely and only when appropriate.</p><h4><strong>Observers Map</strong></h4><p>Observers are stored in mObservers, which is a SafeIterableMap&lt;Observer&lt;? super T&gt;, ObserverWrapper&gt;. We notice that, each Observer is wrapped in an ObserverWrapper that tracks its state and version.</p><h4><strong>Observer Types</strong></h4><p>1. <strong>LifecycleBoundObserver</strong> → Used when observing with a LifecycleOwner.</p><ul><li>The observer is <strong><em>automatically removed</em></strong> when the lifecycle reaches DESTROYED.</li><li>It is considered <strong><em>active</em></strong> only when the lifecycle is at least in the STARTED state.</li></ul><p>2. <strong>AlwaysActiveObserver</strong> → Used when observing with observeForever().</p><ul><li><strong>Always considered active</strong>.</li><li><strong>Must be manually removed</strong> using removeObserver().</li></ul><h4><strong>Versioning Logic (Notifying The Observers)</strong></h4><p>Each observer stores the last version of data it received (in mLastVersion).<br>Okay, so when a new value is set (using setValue()):</p><ul><li>The global mVersion is incremented.</li><li>dispatchingValue() iterates through the observers.</li><li>For each observer, considerNotify() checks:<br>- Is the observer active?<br>- Is mVersion &gt; mLastVersion?</li><li>If both conditions are true, then:<br>- mLastVersion is updated.<br>- and observer.onChanged(mData) is invoked with the latest value.</li></ul><h4><strong>Dispatch Safety (How LiveData solves re-entry issues)</strong></h4><p>LiveData uses 2 internal flags to handle re-entrant updates safely; because well, nobody likes chaos, especially in code:</p><ul><li>mDispatchingValue → Indicates whether LiveData is currently dispatching updates.</li><li>mDispatchInvalidated → Marks that a new value arrived during dispatch; ensures another pass is made <em>after the</em> <em>current dispatch finishes</em>.</li></ul><p>This mechanism guarantees that:</p><ul><li>Observers only receive updates when they are in an <em>active state</em>.</li><li>Each update is delivered <strong><em>at most once</em></strong> per observer.</li><li><em>Updates are never lost</em>, even if new values are set while dispatching is in progress.</li></ul><h3>Wrapping Up</h3><p>And that’s a wrap. We’ve uncovered the not-so-secret sauce behind LiveData’s lifecycle-aware magic: its mData, mVersion, and the clever observer management that keeps it running like a well-oiled Swiss watch.</p><p>But theory alone isn’t enough. In the next post, we’ll roll up our sleeves and build a custom LiveData implementation from scratch. Think of it as “<em>LiveData: The First Draft</em>”; just all the learning, none of the production-ready guarantees.</p><p>By the end of it, you’ll have such a deep understanding of LiveData that you could probably explain it to your grandmother, of-course assuming she’s into Android development.</p><p>Whether you’re sticking with LiveData or migrating to Flow, this knowledge will make you a more thoughtful and effective Android developer.</p><p>Stay tuned. See you in the next one! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41263f8a2a0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kotlin Coroutine Internals: Suspension, Continuations, and State]]></title>
            <link>https://medium.com/@rajabhandari100/kotlin-coroutines-internals-explained-238d09ae7f02?source=rss-3a7d70739aa6------2</link>
            <guid isPermaLink="false">https://medium.com/p/238d09ae7f02</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[coroutine-internals]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Raja Bhandari]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 22:22:16 GMT</pubDate>
            <atom:updated>2025-08-06T22:23:19.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFIWl2QYFJLPAcRcwysYBw.png" /><figcaption>Sorry, I forgot the 1</figcaption></figure><p>If you’ve written asynchronous code in Kotlin recently, you’ve probably used coroutines, they’ve become the go-to approach for handling concurrency in modern Kotlin development. They help us write non-blocking code that still <em>looks</em> like regular, sequential code.</p><p>Still using callbacks? Brave of you. How’s the weather down in callback hell? 😏</p><p>But have you ever wondered <strong>what happens when a coroutine gets suspended</strong>? Or <strong>how suspension actually works under the hood</strong>? <br>Let’s admit it guys, we all have at some point.</p><p>This blog is your guided tour into the world of Kotlin coroutines; not just how to use them, but what makes them tick. We’ll take it step by step, use analogies, peek under the hood, and try to simplify some of the magic behind suspension.</p><p>Let’s start with the basics.</p><h3>1. What is a Suspending Function?</h3><p>In Kotlin, a function marked with the suspend keyword is called a <strong>suspending function</strong>. It’s just like any regular function: it can take parameters, return values, <strong>but it has one superpower</strong>: it can pause its execution (i.e., suspend) and resume later, without blocking the thread it’s running on.</p><p>Here’s a quick example:</p><pre>suspend fun fetchMessage(): String {<br>    delay(1000) // Pretend this waits for a network or file response<br>    return &quot;Helloooo from the other side!&quot;<br>}</pre><p>Looks like an ordinary function, right? But it can pause during the delay call and resume after 1 second (all without freezing the thread).</p><p><strong>But wait, does this function run by itself?<br></strong>Nope. That brings us to the next piece of the puzzle.</p><h3>2. What is a Coroutine?</h3><p>A <strong>coroutine</strong> is the thing that actually runs suspending functions. Think of it as a <strong>lightweight thread; </strong>it’s a unit of work that can run concurrently with other coroutines, but it doesn’t carry the heavyweight baggage of a regular thread.</p><p>Here’s how you’d run the fetchMessage() function using a coroutine:</p><pre>lifecycleScope.launch { // This launches a coroutine tied to a LifecycleOwner<br>    val message = fetchMessage()<br>    println(message)<br>}</pre><p>So, in simple terms:</p><ul><li><strong>Suspending functions</strong> define <em>what</em> can be paused.</li><li><strong>Coroutines</strong> decide <em>how and when</em> to pause or resume.</li></ul><p>A suspending function can’t run without a coroutine, just like a play can’t start without a stage.</p><h3>3. Why Do We Need Both?</h3><p>You might be wondering:</p><blockquote><strong><em>If coroutines are the ones doing all the work, why bother with suspend functions?</em></strong></blockquote><p>First of all, Good question.</p><ul><li>Coroutines manage the <strong>execution: </strong>when to start, pause, or resume.</li><li>Suspend functions define the <strong>pause points</strong>: where in your code it’s okay to stop and come back later.</li></ul><p>We need both to build modern asynchronous programs that are:</p><ul><li><strong>Non-blocking</strong></li><li><strong>Easy to read</strong></li><li><strong>Easy to maintain</strong></li></ul><p>It’s like a partnership; and when they work together, your code looks just like normal synchronous code, but it behaves in a smart, asynchronous way.</p><h3>4. How Coroutine Suspension Works (With an Analogy)</h3><p>Let’s say you’re playing a video game, and you hit a checkpoint. You save the game, turn off your console, and go do something else. When you return, you load the game from where you left off and continue playing.</p><p>That’s <strong>exactly how coroutine suspension works</strong>.</p><p>When a coroutine hits a suspension point (like delay() or a network call), it saves its progress, not in a game file (though that’d be cool, nvm) but in a special object called a <strong>Continuation</strong>. It then steps aside and lets the thread do other useful work.</p><p>When the data or response is ready, the coroutine <strong>resumes</strong> from the exact point it paused.</p><p><strong>Important to note:</strong> Unlike threads, coroutines can pause without blocking any resources. Also, they can resume on a different thread entirely. And that’s what makes them so flexible and efficient.</p><h3>5. Why Do Coroutines Get Suspended?</h3><p>The most common reason is: <strong>waiting</strong>.</p><p>Waiting for a network response, a long computation, or even just a simple timer. In traditional threading, you’d block the thread during this wait, wasting valuable system resources.</p><p>But with coroutines:</p><ul><li>You <strong>suspend</strong> instead of blocking.</li><li>The thread is freed up to do other work.</li><li>Your coroutine <strong>picks up right where it left off</strong> once the data arrives.</li></ul><p>This is the magic of structured concurrency in Kotlin; and it all starts with understanding suspension.</p><blockquote>Note that, we suspend <strong>coroutines</strong>, not <strong>functions</strong>. <br>A suspending function doesn’t suspend itself: it only defines where a coroutine can be suspended.</blockquote><h3>6. What Happens Under the Hood? (Continuation-Passing Style)</h3><p>Now let’s pop open the hood and look at how Kotlin compiles suspending functions internally.</p><p>When you write a suspending function like:</p><pre>suspend fun loadUserProfile(): Profile</pre><p>Kotlin converts it into something like this under the hood:</p><pre>fun loadUserProfile(continuation: Continuation&lt;*&gt;): Any?</pre><p><strong>Hold on!</strong> why does the return type suddenly become Any? instead of Profile??</p><p>Because Kotlin needs to handle <strong>two possibilities</strong>:</p><ol><li>The function completes and returns a regular result (Profile?)</li><li>The function <strong>suspends</strong>, in which case, it returns a special marker: COROUTINE_SUSPENDED</li></ol><p>Since these two outcomes don’t share a specific type, Kotlin chooses their <strong>common supertype, </strong>which is Any?.</p><p>So, under the hood, every suspending function takes a Continuation as a hidden parameter (it’s always added as the last parameter in the function signature) and returns Any? to support both normal and suspended states.</p><h3>7. Let’s Go Deeper: How State Is Tracked in a Suspending Function</h3><p>Consider this suspending function:</p><pre>suspend fun processOrder() {<br>    println(&quot;Order received&quot;)<br>    delay(1000)<br>    println(&quot;Order processed&quot;)<br>}</pre><p>Internally, Kotlin compiles it into a <strong>state machine</strong>. Here’s a simplified version of what that might look like:</p><pre>fun processOrder(outerContinuation: Continuation&lt;Unit&gt;): Any {<br>    // We only want to wrap the continuation once, so we check first<br>    val continuation = if (outerContinuation is OrderContinuation) {<br>        outerContinuation // Reuse the existing continuation if already wrapped<br>    } else {<br>        OrderContinuation(outerContinuation) // Wrap it into our own continuation<br>    }<br>    <br>    when (continuation.label) {<br>        0 -&gt; {<br>            println(&quot;Order received&quot;)<br>            continuation.label = 1 //Set to next state before the suspension below<br>            if (delay(1000, continuation) == COROUTINE_SUSPENDED) {<br>                return COROUTINE_SUSPENDED<br>            }<br>        }<br><br>        1 -&gt; {<br>            println(&quot;Order processed&quot;)<br>            return Unit<br>        }<br><br>        else -&gt; error(&quot;Invalid state&quot;)<br>    }<br>}</pre><p>And the continuation (though it’s not a regular class, it’s actually an <em>anonymous object created by the compiler that extends </em>ContinuationImpl) might look like this:</p><pre>class OrderContinuation(<br>    val completion: Continuation&lt;Unit&gt;<br>) : Continuation&lt;Unit&gt; {<br>    <br>    override val context: CoroutineContext<br>        get() = completion.context<br>    <br>    var label = 0<br>    var result: Result&lt;Any&gt;? = null<br><br>    override fun resumeWith(result: Result&lt;Unit&gt;) {<br>        this.result = result<br>        <br>        val outcome = try {<br>            val res = processOrder(this)<br>            if (res == COROUTINE_SUSPENDED) return<br>            Result.success(res as Unit)<br>        } catch (e: Throwable) {<br>            Result.failure(e)<br>        }<br>        <br>        completion.resumeWith(outcome)<br>    }<br>}</pre><p>To keep track of where to resume from, the compiler-generated state machine uses a field called label. It starts at 0, meaning the function will begin from the top. But just before every suspension point (like delay()), the label is <strong>updated</strong> to the next step.</p><p>That way, if the coroutine gets suspended and later resumed, it knows exactly where to continue, <strong>right after the last suspension point.</strong></p><p><strong><em>And, here’s the interesting part:</em></strong></p><p>When a suspending function like delay() suspends, it returns a special marker called COROUTINE_SUSPENDED. <br>Then, the current function immediately <strong>returns</strong> that same marker to its caller.</p><p>And this continues, all the way up the call stack, until it reaches the coroutine that was originally launched. Only that coroutine knows what to do next.</p><p>This is how <strong>all intermediate functions “pause” without blocking</strong>, and the thread is freed up for other tasks (like running other coroutines).</p><h4>🧪 But… what if delay() didn’t actually suspend? What if it just returned Unit?</h4><p>In that case, the coroutine wouldn’t return early. The code would just flow to the next step, right? no suspension, no pause, no waiting. It would behave just like any other regular, sequential function.</p><p>So the presence of COROUTINE_SUSPENDED is what makes the whole suspension system tick. Without it, the state machine doesn’t need to pause.</p><blockquote>COROUTINE_SUSPENDED is like Kotlin’s secret handshake. When a function returns it, everyone up the call stack just nods and steps aside. <strong>Respect</strong>. 🫡</blockquote><p>🧵 To wrap up this section:</p><ul><li>The label field tracks the current execution step.</li><li>Each suspension point updates the label before pausing/suspending.</li><li>When resumed, the function starts <strong>exactly after</strong> the last suspension point.</li></ul><p>This state machine model allows Kotlin to efficiently suspend and resume execution without complex stack manipulation or thread blocking.</p><h4>🧠 But That Was a Simple Function… What If It Has Local Variables?</h4><p>Consider this suspend function now:</p><pre>suspend fun processOrder() {<br>    println(&quot;Order received&quot;)<br>    var itemsPacked = 0<br>    delay(1000)<br>    itemsPacked++<br>    println(&quot;Items packed so far: $itemsPacked&quot;)<br>    println(&quot;Order processed&quot;)<br>}</pre><p>Here, itemsPacked is a local variable declared inside the function, but it’s needed <strong>both before and after</strong> the suspension point (delay()).</p><p>Since the function can be suspended <strong>after setting </strong>itemsPacked=0, Kotlin needs a way to remember that value when the coroutine resumes.</p><p>So just like it tracks the label, the compiler also stores such local variables (like itemsPacked) as fields inside the generated continuation class (e.g., OrderContinuation).</p><h4>💡 Why is this necessary?</h4><p>Normally, when one function calls another (e.g., first() calls second()), the computer uses the <strong>call stack</strong> to keep track of:</p><ol><li>Where to return after second() finishes</li><li>What the local variables inside first() were</li></ol><p>But with <strong>suspending functions</strong>, we pause execution and free up the thread, and when that happens, the <strong>call stack is cleared</strong>.</p><p>So Kotlin can’t rely on the real stack anymore.</p><p>Instead, Kotlin uses the <strong>continuation object</strong> to store everything the function needs to resume:</p><ul><li>The point where it left off (label)</li><li>Any <strong>local variables and parameters </strong>(as fields)<strong> </strong>used across suspension points</li><li>And a reference to the <strong>previous continuation</strong>, allowing it to return to the caller</li></ul><p>This creates what’s essentially a <strong>“fake call stack”, </strong>which is basically a chain of continuations that allow the program to resume just like it never paused. Pretty smart, right?</p><h3>Final Thoughts</h3><p>Coroutines may look simple on the surface, but they’re backed by a powerful mechanism; a smart, label-based state machine driven by continuations.</p><p>By understanding:</p><ul><li><strong>What</strong> suspend functions are</li><li><strong>How</strong> coroutine suspension and resumption work</li><li><strong>Why</strong> Kotlin uses continuation-passing style internally</li></ul><p>You’ll not only be able to write better coroutine code, but also debug, optimize, and reason about concurrency much more confidently.</p><p>If you’ve made it this far, congrats! You’ve just unlocked the internals of Kotlin coroutines.</p><blockquote><strong>📚 Related Reads That You Might Like</strong></blockquote><blockquote>Learn how threads are managed, reused, and scheduled — and how it connects with coroutine dispatchers: <a href="https://medium.com/@rajabhandari100/understanding-threadpools-in-android-a-hands-on-playground-a674bf006846">https://medium.com/@rajabhandari100/understanding-threadpools-in-android-a-hands-on-playground-a674bf006846</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238d09ae7f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>