<?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 Aakash Gavle on Medium]]></title>
        <description><![CDATA[Stories by Aakash Gavle on Medium]]></description>
        <link>https://medium.com/@gavleaakash?source=rss-dacd13db5ae1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v3K40_IxrlY97BVUEmh4VQ.jpeg</url>
            <title>Stories by Aakash Gavle on Medium</title>
            <link>https://medium.com/@gavleaakash?source=rss-dacd13db5ae1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:44:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gavleaakash/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[How Does ViewModel Survive Configuration Changes?]]></title>
            <link>https://medium.com/@gavleaakash/how-does-viewmodel-survive-configuration-changes-027b8e4b4008?source=rss-dacd13db5ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/027b8e4b4008</guid>
            <category><![CDATA[android-interviews]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-internals]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Aakash Gavle]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 07:32:51 GMT</pubDate>
            <atom:updated>2026-08-16T14:10:00.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vaIxEGINNehT86Pf0CAHA.png" /></figure><p>I don’t think there’s been a single interview where this question wasn’t asked to me. Sometimes the interviewer is happy with a short, direct answer, but most actually want to know whether you understand the internal workings or not. Let’s break this down into small pieces and see if we can build a well-articulated answer, and most importantly, actually verify how it works instead of just repeating what everyone says.</p><h3>1. What is a ViewModel?</h3><p>A ViewModel is a lifecycle-aware component designed to store and manage UI-related data in a way that survives configuration changes like screen rotation, keyboard toggling, or language change.</p><p>When a configuration change happens, Android by default destroys and recreates the hosting Activity or Fragment (yes, onDestroy() gets called). Anything held as a simple field inside the Activity is lost. AViewModel, however, is not owned by the Activity instance; it&#39;s owned by something that outlives it.</p><pre>class MainViewModel : ViewModel() {<br>    var counter = 0<br>}<br><br>class MainActivity : ComponentActivity() {<br>    private val viewModel: MainViewModel by viewModels()<br>}</pre><p>Rotate the device, and counter retains its value. An Activity can&#39;t pull that off on its own, or can it? Let&#39;s find out.</p><h3>2. Deep Dive: What Actually Survives?</h3><p><strong>2.1 The ViewModelStore</strong></p><p>The thing that survives a configuration change isn’t a single ViewModel instance; it’s the ViewModelStore, a container that holds all ViewModels tied to that Activity/Fragment.</p><pre>public class ViewModelStore {<br>    private val map = mutableMapOf&lt;Any?, ViewModel&gt;()<br><br>    public fun put(key: Any?, viewModel: ViewModel) {<br>        val oldViewModel = map.put(key, viewModel)<br>        oldViewModel?.clear()<br>    }<br><br>    public operator fun get(key: Any?): ViewModel? = map[key]<br><br>    public fun clear() {<br>        val snapshot = map.toMap()<br>        map.clear()<br>        for (viewModel in snapshot.values) {<br>            viewModel.clear()<br>        }<br>    }<br>}</pre><p>It’s basically a key-value map. Which brings us to the first follow-up question(Yes, you’re expected to know this and might get asked).</p><p><strong>2.2 What’s the key-value pair?</strong></p><ul><li><strong>Key</strong>: either the default key &quot;androidx.lifecycle.ViewModelProvider.DefaultKey:&quot; + canonicalClassNameor a custom key if you use viewModels(key = &quot;...&quot;).</li><li><strong>Value</strong>: the actual ViewModel instance.</li></ul><p>So a single Activity can hold multiple ViewModels of different types (or the same type under different keys) inside one ViewModelStore.</p><p><strong>2.3 The retention mechanism</strong></p><p>ComponentActivity internally overrides a legacy Activity method, onRetainNonConfigurationInstance()and wraps the ViewModelStore inside a NonConfigurationInstances object:</p><pre>final override fun onRetainNonConfigurationInstance(): Any? {<br>    // Maintain backward compatibility.<br>    val custom = onRetainCustomNonConfigurationInstance()<br>    var viewModelStore = _viewModelStore<br>    if (viewModelStore == null) {<br>        // No one called getViewModelStore(), so see if there was an existing<br>        // ViewModelStore from our last NonConfigurationInstance<br>        val nc = lastNonConfigurationInstance as NonConfigurationInstances?<br>        if (nc != null) {<br>            viewModelStore = nc.viewModelStore<br>        }<br>    }<br>    if (viewModelStore == null &amp;&amp; custom == null) {<br>        return null<br>    }<br>    val nci = NonConfigurationInstances()<br>    nci.custom = custom<br>    nci.viewModelStore = viewModelStore<br>    return nci<br>}</pre><p><strong>Timing matters here.</strong> The restored ViewModelStore isn&#39;t fetched inside onCreate(). It&#39;s fetched via getLastNonConfigurationInstance() insideComponentActivity.attach(), which runs before onCreate() is even called. So by the time your onCreate() runs and you callby viewModels(), the store has already been resolved, new or restored.</p><p>Full flow:</p><pre>Old Activity destroy (config change) -&gt;<br>  onRetainNonConfigurationInstance() saves ViewModelStore -&gt;<br>  Old Activity instance fully destroyed<br>New Activity instance created -&gt;<br>  attach() -&gt; getLastNonConfigurationInstance() restores ViewModelStore -&gt;<br>  onCreate() -&gt; viewModels()/ViewModelProvider() reads from the restored store</pre><p>If the store is empty (fresh launch, or process death), ViewModelProvider creates new instances on demand and stores them.</p><p><strong>2.4 What happens on real destruction (not a config change)?</strong></p><p>isFinishing() is what distinguishes the two internally. On a genuine finish (back press, finish() call), the store&#39;s clear() is called, which triggers onCleared() on every ViewModel it holds, releasing resources, cancelling coroutines, and so on. On a config-change destroy, clear() is not called; the store is just handed forward.</p><h3>3. Who’s the actual ViewModelStoreOwner?</h3><p>ComponentActivity is. It implements interface ViewModelStoreOwner { val viewModelStore: ViewModelStore }.</p><p>Plain Activity (android.app.Activity) does not implement this interface. ViewModelStore is an AndroidX/Jetpack concept, not a framework one.</p><p>InsideComponentActivity, the viewModelStore property is initialized lazily. attach() tries to restore it via getLastNonConfigurationInstance() first, and only creates a fresh ViewModelStore() if there&#39;s nothing to restore.</p><p>A Fragment is its own ViewModelStoreOwner too, with its own store. Use , activityViewModels() and you point at the hosting Activity&#39;s store instead. The two are independent owners, and instances only get shared when the key matches.</p><h3>4. ViewModel Creation and Retrieval</h3><p>The ViewModelProvider checks if an instance already exists in the ViewModelStore for the given key. If it does, that instance is returned; if not, a new one is created via a ViewModelProvider.Factory and stored.</p><h3>5. Follow-Up: What’s inside by viewModels()?</h3><p>by viewModels() is a Kotlin property delegate from androidx.activity.viewModels (or androidx.fragment.app.viewModels for Fragments). Internally it builds a ViewModelLazy:</p><pre>public inline fun &lt;reified VM : ViewModel&gt; ComponentActivity.viewModels(<br>    noinline extrasProducer: (() -&gt; CreationExtras)? = null,<br>    noinline factoryProducer: (() -&gt; Factory)? = null<br>): Lazy&lt;VM&gt; {<br>    val factoryPromise = factoryProducer ?: { defaultViewModelProviderFactory }<br>    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise, extrasProducer)<br>}</pre><p>Worth knowing for an interview:</p><ul><li><strong>viewModelStore</strong>: where the created/retrieved instance is cached. Comes from the Activity itself, retained across config changes as covered above.</li><li><strong>factoryProducer</strong>: the ViewModelProvider.Factory responsible for actually constructing the ViewModel. This is the extension point Hilt hooks into (more below). Defaults todefaultViewModelProviderFactory, which typically uses SavedStateViewModelFactory under the hood so your ViewModel can also receive a SavedStateHandle.</li><li><strong>extrasProducer</strong>: supplies CreationExtras, additional creation-time data (like the SavedStateHandle source, or the owning ViewModelStoreOwner) passed to the factory without needing constructor injection tricks.</li></ul><p>It’s a Lazy&lt;VM&gt;, so the actual ViewModelProvider(store, factory).get(VM::class.java) call only happens the first time you access viewModel, not at declaration time.</p><h3>6. Follow-Up: How does Hilt manage it?</h3><p>@HiltViewModel doesn&#39;t change <em>where</em> the ViewModel lives (still the ViewModelStore). It changes <em>how</em> it&#39;s constructed by swapping the factory.</p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val repository: UserRepository<br>) : ViewModel()</pre><p>Behind the scenes:</p><ol><li>Hilt generates a HiltViewModelFactory that wraps the default factory.</li><li>When you call hiltViewModel() (Compose) or use @AndroidEntryPoint + by viewModels(), the injected factory is what actually gets passed as factoryProducer.</li><li>That factory looks up a Map&lt;Class&lt;out ViewModel&gt;, Provider&lt;ViewModel&gt;&gt; generated at compile time (via Dagger multibinding) to find the right @Inject-annotated constructor for your ViewModel, resolves its dependencies from the Dagger graph, and constructs it.</li><li>The resulting instance still lands in the same ViewModelStore. Hilt doesn&#39;t touch storage or retention at all, only construction.</li></ol><p>So: retention is a Jetpack/AndroidX concern, dependency provisioning is Hilt’s concern. The two are orthogonal.</p><h3>7. Follow-Up: SharedViewModel, how does instance sharing work?</h3><p>A “SharedViewModel” (shared between a Fragment and its parent Activity, or between sibling Fragments) works purely based on <em>which</em> ViewModelStoreOwner you point the ViewModelProvider at. No special API involved.</p><pre>// Scoped to the Fragment itself, each Fragment gets its own instance<br>private val vm: SharedViewModel by viewModels()<br>// Scoped to the parent Activity, every Fragment hosted by it shares one instance<br>private val vm: SharedViewModel by activityViewModels()<br>// Scoped to a parent Fragment (e.g. shared between child Fragments of a nav graph)<br>private val vm: SharedViewModel by viewModels({ requireParentFragment() })<br></pre><p>activityViewModels() simply passes the hosting Activity&#39;s ViewModelStore (instead of the Fragment&#39;s own) into the ViewModelProvider. Since the key (class name) is the same, every Fragment resolving against that store gets back the same instance. That&#39;s the entire mechanism. No event bus, no singleton, just a shared store plus a shared key.</p><p>This is also why Navigation Component’s hiltViewModel(navBackStackEntry) works for nav-graph-scoped ViewModels. It just points at the ViewModelStoreOwner of the NavBackStackEntry instead of the Fragment or Activity.</p><h3>8. Follow-Up: What about process death?</h3><p>This is the trap question. <strong>ViewModelStore does not survive process death.</strong> Configuration change is not the same as process death.</p><ul><li><strong>Configuration change</strong>: Activity is destroyed, but the process stays alive, so the in-memory ViewModelStore can be handed forward via onRetainNonConfigurationInstance().</li><li><strong>Process death</strong> (system kills the app in the background for memory): the entire process, including the ViewModelStore and everything in it, is gone. When the user navigates back, Android spins up a new process and a new Activity with no memory of the old store.</li></ul><p>To survive process death, you need to persist state outside the process:</p><ol><li><strong>SavedStateHandle</strong>, the standard Jetpack solution. Inject it into your ViewModel constructor; it&#39;s backed by the onSaveInstanceState() Bundle mechanism, but exposed through your ViewModel so you don&#39;t have to manually shuttle data through the Activity.</li></ol><pre>class MainViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {<br>    var counter: Int<br>        get() = savedStateHandle[&quot;counter&quot;] ?: 0<br>        set(value) { savedStateHandle[&quot;counter&quot;] = value }<br>}</pre><p>Only small, Parcelable/primitive-safe data should go here, same constraints as Bundle.</p><p>2. <strong>Persistent storage</strong> (Room / DataStore/files) for anything larger, or that needs to survive app restarts and not just process death within a session.</p><p>3. There’s no way to keep an arbitrary in-memory object (like a live ViewModel instance) alive across process death. The OS reclaims the entire process memory space. SavedStateHandle works because it&#39;s the <em>state</em> (not the object) that gets serialized into a Bundle that the system, not your process, holds onto viaActivityManager, and rehydrates when your app relaunches.</p><h3>9. Interview-Ready Answer (Concise Version)</h3><blockquote><em>“ViewModel survives configuration changes because it’s not stored inside the Activity, it’s stored in a </em><em>ViewModelStore, a key-value map of ViewModel instances. </em><em>ComponentActivity is the actual </em><em>ViewModelStoreOwner, and it overrides </em><em>onRetainNonConfigurationInstance() to hand this store forward across a config-change-triggered recreation. The new Activity instance retrieves it in </em><em>attach(), before </em><em>onCreate() runs. On a real destroy (</em><em>isFinishing == true), the store&#39;s </em><em>clear() is called instead, invoking </em><em>onCleared() on every ViewModel and releasing them.</em></blockquote><blockquote><em>This only works because the process stays alive during a configuration change. It does not survive process death, since the OS reclaims the entire process’s memory, store included. For process death, we rely on </em><em>SavedStateHandle, which persists small state via the system-managed Bundle mechanism, separate from the ViewModel instance itself.</em></blockquote><blockquote><em>Dependency injection (Hilt, for instance) is orthogonal to all this. </em><em>@HiltViewModel only swaps the </em><em>ViewModelProvider.Factory used to construct the instance; the instance still lives in, and is retained by, the same </em><em>ViewModelStore.&quot;</em></blockquote><p>That’s it for this time; see you soon with coverage of another topic.</p><p><strong>Connect with me</strong></p><p>I’m Aakash, an Android developer, mostly working with Kotlin, Jetpack Compose, and Clean Architecture. If you want to check out more of my work or just connect:</p><p>GitHub: <a href="https://github.com/aakash-gavle">https://github.com/aakash-gavle</a> <br>LinkedIn: <a href="https://www.linkedin.com/in/aakash-gavle">https://www.linkedin.com/in/aakash-gavle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=027b8e4b4008" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Coroutines in Android]]></title>
            <link>https://medium.com/@gavleaakash/understanding-coroutines-in-android-3b66be64f6d8?source=rss-dacd13db5ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b66be64f6d8</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[machine-coding-round]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aakash Gavle]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 05:04:14 GMT</pubDate>
            <atom:updated>2026-08-01T05:05:15.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmACSb2ae-V5Va3crHrvGA.png" /></figure><h3>Understanding Coroutines in Android</h3><p>Coroutines are something that we use on a day-to-day basis and are asked in an interview almost every single time. We straight up answer that Coroutines are lightweight threads used for asynchronous coding and don’t block the thread in a suspended state … But what actually makes coroutines lightweight? How is it different from a conventional thread? Let’s deep dive into coroutines…</p><p>Before diving into coroutines, let’s first figure out what a suspend function actually is.</p><h3>1. What is a suspend function?</h3><p>A suspend function is just a regular Kotlin function with one extra ability, it can <strong>pause</strong> its execution without blocking the thread, and <strong>resume</strong> later, possibly on a different thread.</p><p>You can only call a suspend function from another suspend function or from a coroutine (launch/async).<br> <br>But how can it actually be able to pause and resume?</p><p>You can check this yourself in Android Studio: <strong>Tools → Kotlin → Show Kotlin Bytecode → Decompile</strong>. If you decompile a suspend function, this is roughly what you’ll see:</p><pre>    suspend fun fetchCharacter(id: Int): Character {<br>        return uiState.value[id]<br>    }</pre><p>compiles down to:</p><pre>   @Nullable<br>   public final Object fetchCharacter(int id, @NotNull Continuation $completion) {<br>      return ((List)this.uiState.getValue()).get(id);<br>   }</pre><p>Now that we know that the compiler passes an extra parameter of Continuation type… So what is it?</p><h3>2. Continuation Passing Style (CPS)</h3><p>Every suspend function is compiled by Kotlin into a regular function that takes one extra hidden parameter: a Continuation. This is what actually enables the &quot;pause and resume&quot; behavior — the Continuation is essentially a callback that knows how to resume execution exactly where it left off, along with the result (or exception) of the suspended operation.</p><h3>3. What actually happens when a coroutine suspends</h3><p>This is where I used to get stuck most so let’s break it down:</p><ol><li>Coroutine hits a suspension point (e.g. a network call via delay() or Retrofit&#39;s suspend function)</li><li>Its current state, local variables, and where it was in the code get saved into the Continuation</li><li>The thread it was running on is <strong>released back to the thread pool</strong>, free to pick up other coroutines(Imp)</li><li>Once the suspended work finishes, the coroutine is scheduled again (possibly on a <em>different</em> thread from the pool)</li><li>Execution resumes exactly where it left off, using the saved state</li></ol><p>Internally, the compiler transforms your suspend function into a <strong>state machine</strong> — each suspension point becomes a case in a when/switch block, and the Continuation tracks which case to jump into on resume. That&#39;s why you never see raw callback nesting in coroutine code; the compiler is doing that bookkeeping for you.</p><p>Decompiled bytecode example :</p><pre>public final void fetchData() {<br>   BuildersKt.launch$default(this.scope, (CoroutineContext)null, (CoroutineStart)null, new Function2((Continuation)null) {<br>      int label;<br><br>      public final Object invokeSuspend(Object $result) {<br>         Object var2 = IntrinsicsKt.getCOROUTINE_SUSPENDED();<br>         switch (this.label) {<br>            case 0:<br>               ResultKt.throwOnFailure($result);<br>               CharacterViewModel var10000 = CharacterViewModel.this;<br>               Continuation var10002 = (Continuation)this;<br>               this.label = 1;<br>               if (var10000.fetchCharacter(1, var10002) == var2) {<br>                  return var2;<br>               }<br>               break;<br>            case 1:<br>               ResultKt.throwOnFailure($result);<br>               break;<br>            default:<br>               throw new IllegalStateException(&quot;call to &#39;resume&#39; before &#39;invoke&#39; with coroutine&quot;);<br>         }<br><br>         return Unit.INSTANCE;<br>      }</pre><h3>4. Coroutines are lightweight threads</h3><p>A thread on Android costs roughly 1MB of stack memory and is managed by the <strong>OS scheduler</strong>. <br>A coroutine costs a few KB and is managed by Kotlin’s own runtime; we can launch tens of thousands of coroutines on a handful of actual threads without breaking a sweat.</p><p>Be mindful that coroutines don’t replace threads; they work on top of them. Kotlin’s coroutine machinery decides when a coroutine actually needs a thread and hands it one from a pool, then takes it back the moment the coroutine suspends.</p><h3>5. Scope, Job, and SupervisorJob</h3><p><strong>CoroutineScope: K</strong>eeps track of all coroutines launched within it and ties them to a lifecycle. Cancel the scope, and everything launched inside it gets cancelled too.</p><p><strong>Job</strong>: Represents the actual unit of work running inside a scope. Every coroutine you launch returns a Job (or a Deferred, which is a Job that also carries a result).</p><p><strong>SupervisorJob: L</strong>aunched via a <strong>supervisor scope</strong> so that if one child fails, it doesn’t cancel its siblings or propagate the failure up to the parent. A regular Job fails the whole tree; a SupervisorJob isolates failures per child.</p><pre>val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)</pre><h3>6. launch vs async/await</h3><p><strong>launch</strong> : fire and forget. Returns aJob, doesn&#39;t return a result. Use this when you don&#39;t need anything back from the coroutine (e.g., writing to a database, updating UI).</p><p><strong>async / </strong><strong>await</strong> : returns aDeferred&lt;T&gt;, which you call .await() on to get the actual result. Use this when you need a value back, especially when running multiple things in parallel:</p><pre>val user = async { fetchUser() }<br>val posts = async { fetchPosts() }<br>val result = user.await() to posts.await() // both ran concurrently</pre><p><strong>Worth Noting:</strong> exceptions inside async are held until you call .await()they won&#39;t crash your app immediately like launch would. So if we don’t call await()/awaitAll(), the app won&#39;t crash.</p><h3>7. Dispatchers ?? deciding which thread you run on</h3><p>A Dispatcher decides which thread pool a coroutine runs on:</p><ul><li><strong>Dispatchers.Main</strong> the UI thread, for touching views</li><li><strong>Dispatchers.IO</strong> optimized for blocking I/O (network, disk), backed by a larger elastic thread pool</li><li><strong>Dispatchers.Default </strong>CPU-intensive work (sorting, parsing, computation)</li><li><strong>Dispatchers.Unconfined </strong>starts in the caller&#39;s thread, resumes in whatever thread the suspension point resumed on (Used in debug builds; usually avoid using them in release builds)</li><li><strong>Dispatchers.Main.immediate </strong>same as Main, but avoids an unnecessary post-to-queue</li></ul><p><strong>withContext</strong> is how you switch dispatchers mid-coroutine, without needing to launch a new one:</p><pre>suspend fun loadCharacters(): Character = withContext(Dispatchers.IO) {<br>    api.fetchCharacters() // runs on IO, returns back to caller&#39;s original dispatcher<br>}</pre><h3>8. Custom scopes?</h3><p>If we create our own CoroutineScope (outside of viewModelScope/lifecycleScope), we own its lifecycle, which means we&#39;re responsible for cancelling it, or we&#39;ll leak coroutines.</p><pre>val scope = CoroutineScope(Job() + handler)</pre><pre>// don&#39;t forget after work is done or at cleanup time<br>scope.cancel()</pre><h3>9. Exception handling</h3><p>Two ways to handle exceptions in coroutines:</p><ul><li><strong>try/catch</strong> Works as expected inside a coroutine body, same as regular Kotlin code</li><li><strong>CoroutineExceptionHandler</strong> A context element that catches <em>uncaught</em> exceptions at the root of a coroutine hierarchy. Only works withlaunch, not async (since async exceptions surface via .await() instead)</li></ul><pre>val handler = CoroutineExceptionHandler{_, error -&gt;<br>    Log.e(&quot;COROUTINE_ERROR&quot;, &quot;Caught Exception $error&quot;)<br>}<br><br>val scope = CoroutineScope(SupervisorJob() + handler)</pre><h3>10. What’s viewModelScope and lifecycleScope?</h3><p>Both viewModelScope and lifecycleScope are backed by a SupervisorJob under the hood, and both are tied to a lifecycle:</p><ul><li>viewModelScope cancels automatically when the ViewModel is cleared</li><li>lifecycleScope cancels automatically when the Activity/Fragment&#39;s lifecycle is destroyed</li></ul><p>This is why one failed child coroutine inside viewModelScope doesn&#39;t take down every other coroutine running in that ViewModel; the SupervisorJob isolates the failure.</p><h3>11. Structured concurrency?</h3><p>This is the principle that holds the whole system together: <strong>every coroutine has a parent, and no coroutine can outlive its parent’s scope.</strong></p><ul><li>Cancellation flows <strong>down:</strong> cancel the parent, all children get cancelled</li><li>Exceptions flow <strong>up: </strong>a child failing propagates up to the parent (unless isolated by a SupervisorJob)</li></ul><p>That’s it for this time; see you soon with coverage of another topic.</p><p><strong>Connect with me</strong></p><p>I’m Aakash, an Android developer, mostly working with Kotlin, Jetpack Compose, and Clean Architecture. If you want to check out more of my work or just connect:</p><p>GitHub: <a href="https://github.com/aakash-gavle">https://github.com/aakash-gavle</a> LinkedIn: <a href="https://www.linkedin.com/in/aakash-gavle">https://www.linkedin.com/in/aakash-gavle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b66be64f6d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Activity launch modes in Android]]></title>
            <link>https://medium.com/@gavleaakash/understanding-activity-launch-modes-in-android-69a3f2f19fc1?source=rss-dacd13db5ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/69a3f2f19fc1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-activity]]></category>
            <category><![CDATA[android-interviews]]></category>
            <dc:creator><![CDATA[Aakash Gavle]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 05:44:55 GMT</pubDate>
            <atom:updated>2026-07-24T05:44:55.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swd6HsVrSASHD-r72vzx7Q.png" /></figure><p>Activity Launch modes decide how an Activity is instantiated and managed in the back stack.</p><p>There are mainly <strong>5 Launch Modes</strong> in Android (<em>singleInstancePerTask</em> is a new addition)</p><p>It’s important to understand what’s the need for different launch modes in detail, as it’s one of the hot topics that often gets asked in interviews as well as when you decide to create a new application or add a new Activity to your existing project.</p><p>Full Code here for playing around with launch modes: <a href="https://github.com/aakash-gavle/Launch-Modes">https://github.com/aakash-gavle/Launch-Modes</a></p><ol><li><strong>standard<br></strong>This is the default mode if nothing is specified explicitly in the manifest file. A new instance of the activity gets created every time, even if one already exists. <br>Activity stack example : A-&gt;B-&gt;A-&gt;A<br>Use case: Use this for things like e-commerce product details or social media threads, where you might want to stack multiple views and trace back through them</li><li><strong>singleTop</strong><br>This mode creates a new instance UNLESS the same activity is already at the top.<br>Activity stack example: A-&gt;B-&gt;A(A is not on top, so new instance, but if we launch A now it will reuse the old instance. We’ll come back to that later how that is handled) <br>Use case: Search Screens, Chat Screens</li><li><strong>singleTask</strong><br>This mode allows only one instance of activity per app.<br>When triggered, it pops and destroys all activities sitting on top of it in the back stack.<br>Activity stack example: A-&gt;B-&gt;C-&gt;A (A is singleTask and already exists at the root, so it won&#39;t create a new instance. Instead, B and C get popped and destroyed, leaving just the original A at the front.)<br>Use case: Home Screen</li><li><strong>SingleInstance</strong><br>This mode allows only one instance of the activity across the ENTIRE device. It’s highly exclusive.<br>Activity stack example:<br><strong>Task 1:</strong> A -&gt; B <br><strong>Action:</strong> Launch Activity C (set to singleInstance) <br><strong>Result:</strong> Task 1 remains A -&gt; B, and a new <strong>Task 2</strong> is created containing only C.<br><strong>Action:</strong> Activity C launches Activity D <br><strong>Result:</strong> D <em>does not</em> go into Task 2. Instead, D is pushed back into Task 1 (making it A -&gt; B -&gt; D) or into a completely new task, keeping Task 2 completely isolated with just C inside it.</li><li><strong>singleInstancePerTask</strong><br>This mode lets the activity run as the root of a task, but you can have multiple instances running concurrently across entirely different tasks. Activity stack example: Task 1: A, Task 2: A (A is singleInstancePerTask. It exists multiple times globally, but each instance sits at the root of its own separate task.) <br>Use case: Multi-window document editors (like Google Docs), Web browser tabs</li></ol><p><strong>The Golden Rule: Update Your Intent<br></strong>When you reuse an activity (like with singleTop or singleTask), you will often handle new incoming data through onNewIntent(). You must manually update the stored intent here, or you will end up displaying stale data from the previous launch.</p><pre>override fun onNewIntent(intent: Intent) {<br>    super.onNewIntent(intent)<br>    setIntent(intent)<br>    handleIntentPayload(intent)<br>}</pre><p>That’s it for this time; see you soon with coverage of another topic. If there’s something that is not correct or should be included, do let me know.</p><p><strong>Connect with me</strong></p><p>I’m Aakash — Android developer, mostly working with Kotlin, Jetpack Compose, and Clean Architecture. If you want to check out more of my work or just connect:</p><p>GitHub: <a href="https://github.com/aakash-gavle">https://github.com/aakash-gavle</a><br>LinkedIn: <a href="https://www.linkedin.com/in/aakash-gavle/">https://www.linkedin.com/in/aakash-gavle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69a3f2f19fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search with Pagination in Android]]></title>
            <link>https://medium.com/@gavleaakash/search-with-pagination-in-android-f2322ecc9642?source=rss-dacd13db5ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2322ecc9642</guid>
            <category><![CDATA[machine-coding-round]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android-pagination]]></category>
            <category><![CDATA[android-interviews]]></category>
            <dc:creator><![CDATA[Aakash Gavle]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 03:27:56 GMT</pubDate>
            <atom:updated>2026-07-13T03:56:54.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xyW7Gp0FnDve4RkSyiPHw.jpeg" /></figure><h3>Search + Pagination in Android.A Pattern You’ll Reuse Everywhere</h3><p><strong>What is Pagination? <br></strong>Pagination is loading list data in small chunks (pages) instead of all at once, fetching the next chunk as user scrolls near the end.</p><p>I built a small app on top of the Rick and Morty API to dive into this properly , full code here : <a href="https://github.com/aakash-gavle/RickMortyPagination">https://github.com/aakash-gavle/RickMortyPagination</a></p><p><strong>Types of pagination</strong></p><p>There are several ways to do pagination :</p><ol><li><strong>Offset-based</strong> : (page number / offset+limit) ask for “page 3” or “skip 40, give next 20”. Simple, what Rick and Morty API uses, what we’re using here. Problem — if data changes while scrolling (item added/removed), “page 3” doesn’t mean the same thing anymore, so you get duplicates or skipped items.</li><li><strong>Cursor-based :</strong>(token pointing to “where you left off”) instead of a page number, API gives a cursor, you just say “next batch after this”. Handles changing data much better since it’s not depending on a fixed offset.</li><li><strong>Keyset pagination </strong>: same idea as cursor, but uses a real field (last seen ID, timestamp) instead of an opaque token. Mostly a DB-level thing OFFSET gets slow on big tables since DB has to skip N rows every time, keyset avoids that.</li></ol><p><strong>When to use which</strong> — offset is fine for smaller/mostly-static data, simplicity over perfect consistency (our case here). Cursor/keyset for live feeds, chat, anything changing while people scroll — that’s why Twitter/Instagram use cursor-based.</p><p><strong>What can go wrong?</strong></p><p>First thing I tried, obvious mistake — filtering the list already loaded on device. Wrong. If only page 1 (20 items) is loaded and the search match is on page 40, local filter finds nothing. Looks like a bug, isn’t just filtering the wrong data.</p><p>Search has to hit the API directly, search term goes with every page request. So typing in the search box isn’t “filtering a list”, it’s a fresh pagination sequence, just scoped to a name now.</p><p><strong>Layer by layer</strong></p><p><strong>Data layer</strong> — the API call just gets an extra optional param:</p><pre>interface RickAndMortyApi {<br>    @GET(&quot;character&quot;)<br>    suspend fun getCharacters(<br>        @Query(&quot;page&quot;) page: Int,<br>        @Query(&quot;name&quot;) name: String? = null<br>    ): CharacterResponseDto<br>}</pre><p><strong>PagingSource</strong> takes the query and passes it through on every load:</p><pre>class CharacterPagingSource(<br>    private val api: RickAndMortyApi,<br>    private val query: String<br>) : PagingSource&lt;Int, Character&gt;() {</pre><pre>override suspend fun load(params: LoadParams&lt;Int&gt;): LoadResult&lt;Int, Character&gt; {<br>        val page = params.key ?: 1<br>        return try {<br>            val response = api.getCharacters(page, name = query.ifBlank { null })<br>            LoadResult.Page(<br>                data = response.results.map { it.toDomain() },<br>                prevKey = if (page == 1) null else page - 1,<br>                nextKey = if (response.info.next == null) null else page + 1<br>            )<br>        } catch (e: IOException) {<br>            LoadResult.Error(e)<br>        } catch (e: HttpException) {<br>            if (e.code() == 404) LoadResult.Page(emptyList(), null, null)<br>            else LoadResult.Error(e)<br>        }<br>    }</pre><pre>override fun getRefreshKey(state: PagingState&lt;Int, Character&gt;): Int? {<br>        return state.anchorPosition?.let { anchorPosition -&gt;<br>            val anchorPage = state.closestPageToPosition(anchorPosition)<br>            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)<br>        }<br>    }<br>}</pre><p>Quick breakdown, since I used to copy-paste such things without actually getting:</p><ol><li><strong>params.key : </strong>“which page am I on”. Null on first load, defaults to page 1. After that Paging just feeds back whatever we set as nextKey/prevKey — source itself doesn’t track state.</li><li><strong>prevKey / nextKey : </strong>how Paging knows if there’s more to load either direction. prevKey null = start of list, nextKey null = last page, stop. Using response.info.next == null for that — API tells us directly, no guessing off empty results.</li><li><strong>getRefreshKey</strong> : easy one to skip understanding. Matters when list reloads from a specific spot instead of page 1 — say pull-to-refresh while sitting at item 60. Paging uses anchorPosition (roughly what’s visible on screen) to figure out which page to reload around, instead of snapping back to top.</li><li><strong>404 Error?</strong> Rick and Morty API throws a 404 when name search matches nothing, instead of an empty results array. Skip that check and your “no results” search looks like a crash. Every API has some version of this, worth checking early.</li></ol><p><strong>Domain layer</strong> stays boring on purpose, doesn’t know Paging exists.</p><pre>interface CharacterRepository {<br>    fun getCharacters(query : String) : Flow&lt;PagingData&lt;Character&gt;&gt;<br>}</pre><p><strong>Repository</strong> is where PagingSource gets wired into a Pager:</p><pre>class CharacterRepositoryImpl @Inject constructor(<br>    private val api : RickAndMortyApi<br>) : CharacterRepository {</pre><pre>override fun getCharacters(query: String): Flow&lt;PagingData&lt;Character&gt;&gt; {<br>        return Pager(<br>            config = PagingConfig(pageSize = 20, enablePlaceholders = false),<br>            pagingSourceFactory = { CharacterPagingSource(api, query)<br>            }<br>        ).flow<br>    }<br>}</pre><p>pagingSourceFactory is a lambda, not a single instance, on purpose — query changes, Paging needs a fresh PagingSource each time (old one invalidated), so it calls the factory again instead of reusing one. Same reason query sits in the closure instead of some mutable field — new query, new factory call, clean state.</p><p>pageSize = 20 matches what the API actually returns. enablePlaceholders = false since total count isn’t known reliably upfront to render skeletons correctly.ViewModel is where the actual “search” behavior lives, not the PagingSource:</p><pre>@HiltViewModel<br>class CharacterViewModel @Inject constructor(<br>    repository: CharacterRepository<br>) : ViewModel()<br>{</pre><pre>private val _searchQuery = MutableStateFlow(&quot;&quot;)<br>    val searchQuery : StateFlow&lt;String&gt; = _searchQuery.asStateFlow()</pre><pre>@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)<br>    val characters : Flow&lt;PagingData&lt;Character&gt;&gt; = _searchQuery<br>        .debounce(300)<br>        .distinctUntilChanged()<br>        .flatMapLatest { query -&gt; repository.getCharacters(query) }<br>        .cachedIn(viewModelScope)</pre><pre>fun onSearchQueryChanged(newQuery: String) {<br>        _searchQuery.value = newQuery<br>    }<br>}</pre><p>Analysing viewmodel:</p><p><em>debounce</em>(300) : without this you’re firing a network call on literally every keystroke. Nobody’s list needs to react to “r”, then “ri”, then “ric” separately.</p><p><em>flatMapLatest : </em>It cancels whatever was in flight the moment a new value comes in.</p><p>UI side, nothing fancy here, just a TopAppBar with a text field, and the usual LazyColumn + collectAsLazyPagingItems() for rendering, with loadState handled for refresh vs append separately (refresh = whole list reloading because of new search, append = loading next page while scrolling — treat them differently or your loading spinners will show up in the wrong place).</p><p>Things I’d tell anyone building this:</p><p>Don’t filter locally — always let the API do it, pagination and search are the same request cycle, not two features bolted together.</p><p>Handle the “matches nothing” case explicitly for whatever API you’re using. Check what it actually returns, don’t assume it’s a clean empty array.</p><p>Keep the PagingSource dumb, it shouldn’t know about debouncing or UI state, just “given a page and a query, fetch data.” All the smart decision-making about when to fetch belongs in the ViewModel.</p><p><strong>Connect with me</strong></p><p>I’m Aakash — Android developer, mostly working with Kotlin, Jetpack Compose, and Clean Architecture. If you want to check out more of my work or just connect:</p><p>GitHub: <a href="https://github.com/aakash-gavle">https://github.com/aakash-gavle</a> <br>LinkedIn: <a href="https://www.linkedin.com/in/aakash-gavle/">https://www.linkedin.com/in/aakash-gavle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2322ecc9642" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>