<?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 Jyoti Sheoran on Medium]]></title>
        <description><![CDATA[Stories by Jyoti Sheoran on Medium]]></description>
        <link>https://medium.com/@jyotibhambhu?source=rss-8bb3f282f6e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fsjhNueWTdheGgm-VOclng.png</url>
            <title>Stories by Jyoti Sheoran on Medium</title>
            <link>https://medium.com/@jyotibhambhu?source=rss-8bb3f282f6e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:41:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jyotibhambhu/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[Generics in Kotlin: Understanding Invariance, Covariance, and Contravariance]]></title>
            <link>https://jyotibhambhu.medium.com/generics-in-kotlin-understanding-invariance-covariance-and-contravariance-b7e974ffd854?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7e974ffd854</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-02-20T03:31:01.271Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how type relationships work in generic code is one of those things that <em>feels confusing</em> until you see it from the right perspective. Kotlin’s <strong>design for generics</strong> makes this much clearer because it explicitly marks variance where the generic type is declared. Once you internalize that, the equivalent Java syntax will make perfect sense.</p><h3>1. What These Terms Mean (Conceptually)</h3><p>Before writing any code, it helps to understand what we’re trying to capture:</p><ul><li><strong>Invariance</strong> means: no substitution allowed<br>A container with one type cannot be used as a container of another type — even if the types are related.</li><li><strong>Covariance</strong> means: <em>same direction</em> substitution<br>If one type is a subtype of another, then a <em>container</em> of the first can be used where a <em>container</em> of the second is expected.</li><li><strong>Contravariance</strong> means: <em>opposite direction</em> substitution<br>If one type is a subtype of another, then a container of the <em>supertype</em> can be used where a container of the <em>subtype</em> is expected.</li></ul><p>These are abstract terms from type theory, and Kotlin gives us keywords that map exactly to these meanings.</p><h3>2. Invariance in Kotlin (Default Behavior)</h3><p>In Kotlin, <strong>generic types are invariant by default</strong> — that means there is <em>no automatic relationship</em> between generic types even if the underlying types are related. (<a href="https://kotlinlang.org/docs/generics.html?utm_source=chatgpt.com">Kotlin</a>)</p><h3>Example</h3><pre>class Box&lt;T&gt;(var value: T)</pre><pre>fun main() {<br>    val dogBox: Box&lt;Dog&gt; = Box(Dog())<br>    val animalBox: Box&lt;Animal&gt; = dogBox // ❌ Compile-time error<br>}</pre><p>Even though Dog inherits from Animal, a Box&lt;Dog&gt; is <strong>not</strong> a Box&lt;Animal&gt;. Because inside Box, the type T could be used for both producing and consuming values, so allowing substitution could break type safety. (<a href="https://www.kotlinprimer.com/classes-what-we-know-from-java/generics/covariance-contravariance-invariance/?utm_source=chatgpt.com">The Kotlin Primer</a>)</p><p>This is <strong>invariance</strong> — no substitution either way.</p><h3>3. Covariance in Kotlin (out)</h3><p>Covariance lets a container of a more specific type be used where a container of a more general type is expected. In Kotlin, this is expressed with the out keyword on the type parameter. (<a href="https://kotlinlang.org/docs/generics.html?utm_source=chatgpt.com">Kotlin</a>)</p><p>Think of it as a <strong>producer</strong> — something that only gives values out.</p><h3>Example</h3><pre>class Producer&lt;out T&gt;(private val value: T) {<br>    fun produce(): T = value<br>}</pre><pre>fun main() {<br>    val dogProducer = Producer(Dog())<br>    val animalProducer: Producer&lt;Animal&gt; = dogProducer // ✅ Allowed<br>}</pre><p>Why does this work? Because the Producer only returns values (it produces), it never consumes values of type T. So it is safe to say a Producer&lt;Dog&gt; <em>can be treated as</em> a Producer&lt;Animal&gt;.</p><p>This is <strong>covariance</strong> — the container’s relationship follows the same direction as the underlying type hierarchy.</p><h3>4. Contravariance in Kotlin (in)</h3><p>Contravariance lets a container of a more general type be used where a container of a more specific type is expected. In Kotlin, this is expressed with the in keyword on the type parameter.</p><p>Think of it as a <strong>consumer</strong> — something that only accepts values.</p><h3>Example</h3><pre>class Consumer&lt;in T&gt; {<br>    fun consume(item: T) {<br>        println(&quot;Consumed $item&quot;)<br>    }<br>}</pre><pre>fun main() {<br>    val animalConsumer: Consumer&lt;Animal&gt; = Consumer()<br>    val dogConsumer: Consumer&lt;Dog&gt; = animalConsumer // ✅ Allowed<br>}</pre><p>Here, a consumer that can accept <strong>any Animal</strong> can certainly accept a Dog. So Consumer&lt;Animal&gt; can be used as a Consumer&lt;Dog&gt;.</p><p>This is <strong>contravariance</strong> — relationships go in the opposite direction of the type hierarchy.</p><h3>5. Why Kotlin’s Approach Is Powerful</h3><p>Kotlin’s out and in:</p><ul><li>Make the variance intent clear at the declaration site</li><li>Restrict how the type parameter can be used (only out/only in)</li><li>Avoid the need for complex syntax later when using the type</li></ul><p>Contrast this with Java, where variance is declared <em>at the usage point</em> instead of at the declaration.</p><h3>6. Mapping Kotlin Variance to Java</h3><p>Now that you understand the concepts clearly through Kotlin’s explicit markers, let’s see how Java expresses the same ideas in its syntax.</p><p>Java does not have in and out at declaration site. Instead, variance is expressed on <em>uses</em> of generic types using <strong>wildcards</strong>.</p><pre>| Kotlin Declaration-Site | Java Use-Site Equivalent | Meaning        |<br>| ----------------------- | ------------------------ | -------------- |<br>| `out T`                 | `? extends T`            | Covariance     |<br>| `in T`                  | `? super T`              | Contravariance |<br>| no marker               | plain `T`                | Invariance     |</pre><h3>Covariance in Java (? extends)</h3><p>Equivalent to Kotlin’s out.</p><pre>List&lt;? extends Animal&gt; animals = new ArrayList&lt;Dog&gt;();<br>Animal a = animals.get(0); // Allowed<br>// animals.add(new Dog()); // Not allowed</pre><p>Here we can read, but we cannot safely add because we don’t know the actual subtype. This matches the idea of a <strong>producer</strong>. This is the same concept as Kotlin’s out.</p><h3>Contravariance in Java (? super)</h3><p>Equivalent to Kotlin’s in.</p><pre>List&lt;? super Dog&gt; dogs = new ArrayList&lt;Animal&gt;();<br>dogs.add(new Dog()); // Allowed<br>Object o = dogs.get(0); // Only returns Object</pre><p>The list can consume Dogs (because any supertype of Dog can accept Dogs), but you cannot safely retrieve a Dog because the actual list could be of Object or Animal. This is the same idea as Kotlin’s in.</p><h3>Invariance in Java</h3><p>Just like Kotlin, Java assumes <strong>no substitution</strong> unless variance is explicitly applied.</p><pre>List&lt;Dog&gt; dogList = new ArrayList&lt;&gt;();<br>List&lt;Animal&gt; animalList = dogList; // Compile-time error</pre><p>Because Java generics are invariant by default.</p><h3>7. Why This Mapping Helps You Remember</h3><p>Once you learn Kotlin’s in and out:</p><ul><li>out = only returns values (producer) → covariance</li><li>in = only consumes values → contravariance</li><li>no marker = read and write → invariant</li></ul><p>You can memorize Java equivalents in one shot:</p><ul><li>Covariance → ? extends</li><li>Contravariance → ? super</li><li>Invariance → plain generic type</li></ul><p>Seeing Kotlin <em>first</em> builds an intuitive mental model; Java <em>syntax</em> becomes a mechanical mapping.</p><h3>Common Pitfalls and Real-World Collection Examples</h3><p>By now, you understand <strong>what invariance, covariance, and contravariance mean</strong>.<br>This section focuses on <strong>where developers actually get stuck in real code</strong> — not theory.</p><h3>Pitfall 1: “But I only want to read from the list”</h3><h3>Kotlin example</h3><pre>open class Animal<br>class Dog : Animal()</pre><pre>fun printAnimals(animals: List&lt;Animal&gt;) {<br>    animals.forEach { println(it) }<br>}</pre><pre>val dogs: List&lt;Dog&gt; = listOf(Dog(), Dog())</pre><pre>printAnimals(dogs) // Works</pre><p>Why this works:</p><ul><li>List&lt;T&gt; in Kotlin is <strong>read-only</strong></li><li>Kotlin declares List as <strong>covariant</strong> (List&lt;out T&gt;)</li><li>If you only read, covariance is safe</li></ul><p><strong>Mental model:</strong></p><blockquote><em>“If I promise not to modify it, Kotlin lets me widen the type.”</em></blockquote><h3>Java equivalent</h3><pre>void printAnimals(List&lt;? extends Animal&gt; animals) {<br>    for (Animal a : animals) {<br>        System.out.println(a);<br>    }<br>}</pre><p>In Java:</p><ul><li>You must <strong>explicitly say</strong> “I only read”</li><li>? extends Animal communicates that promise</li></ul><h3>Pitfall 2: “Why can’t I add a Dog here?”</h3><h3>Kotlin example</h3><pre>fun addDog(animals: List&lt;Animal&gt;) {<br>    // animals.add(Dog()) ❌ compile error<br>}</pre><p>Why?</p><ul><li>List is read-only</li><li>Even if the actual list is mutable, Kotlin blocks writes</li></ul><p>To add elements:</p><pre>fun addDog(animals: MutableList&lt;Animal&gt;) {<br>    animals.add(Dog()) // Works<br>}</pre><p>But now:</p><pre>val dogs: MutableList&lt;Dog&gt; = mutableListOf(Dog())<br>addDog(dogs) // ❌ does not compile</pre><p>Why?</p><ul><li>MutableList&lt;T&gt; is <strong>invariant</strong></li><li>Writes make variance unsafe</li></ul><p><strong>Mental model:</strong></p><blockquote><em>“If I can write into it, the type must be exact.”</em></blockquote><h3>Java equivalent</h3><pre>void addDog(List&lt;? super Dog&gt; animals) {<br>    animals.add(new Dog());<br>}</pre><p>Here:</p><ul><li>? super Dog means “I only care that I can put Dogs in”</li><li>Reading becomes unsafe (you only get Object)</li></ul><h3>Pitfall 3: Confusing “can hold” with “is a subtype”</h3><p>Many developers think:</p><pre>Dog extends Animal<br>So List&lt;Dog&gt; should extend List&lt;Animal&gt;</pre><p>This is <strong>false</strong>.</p><p>Why?</p><pre>List&lt;Dog&gt; dogs = new ArrayList&lt;&gt;();<br>List&lt;Animal&gt; animals = dogs; // ❌ not allowed</pre><pre>animals.add(new Cat()); // would break dogs</pre><p>The type system prevents this <strong>before runtime</strong>.</p><p><strong>Key rule:</strong></p><blockquote><em>“Containment does not imply substitutability.”</em></blockquote><h3>Pitfall 4: Star projections in Kotlin feel magical</h3><pre>fun printAnything(list: List&lt;*&gt;) {<br>    list.forEach { println(it) }<br>}</pre><p>What List&lt;*&gt; really means:</p><ul><li>“I don’t know the exact type”</li><li>You can read as Any?</li><li>You cannot write anything except null</li></ul><p>Equivalent Java:</p><pre>void printAnything(List&lt;?&gt; list) {<br>    for (Object o : list) {<br>        System.out.println(o);<br>    }<br>}</pre><p><strong>Mental model:</strong></p><blockquote><em>“Unknown type = read-only, safest possible access.”</em></blockquote><h3>Real-World Use Cases (Where This Actually Matters)</h3><h3>1. Logging / Analytics pipelines</h3><ul><li>You <strong>consume</strong> events</li><li>You don’t modify them</li></ul><p>Covariance (List&lt;out Event&gt; / List&lt;? extends Event&gt;)</p><h3>2. Builders / Collectors</h3><ul><li>You <strong>add</strong> items</li><li>You don’t care about exact subtype</li></ul><p>Contravariance (MutableList&lt;in Dog&gt; / List&lt;? super Dog&gt;)</p><h3>3. Business logic transformations</h3><ul><li>You both read and write</li></ul><p>Invariance (MutableList&lt;T&gt; / List&lt;T&gt;)</p><h3>One Table to Remember Everything</h3><pre>| Use case     | Kotlin              | Java          | Why            |<br>| ------------ | ------------------- | ------------- | -------------- |<br>| Only read    | `List&lt;out T&gt;`       | `? extends T` | Safe to widen  |<br>| Only write   | `MutableList&lt;in T&gt;` | `? super T`   | Safe to narrow |<br>| Read + write | `MutableList&lt;T&gt;`    | `List&lt;T&gt;`     | Must be exact  |</pre><h3>Summary</h3><pre>| Concept       | Kotlin keyword | Java syntax   | Behavior        |<br>| ------------- | -------------- | ------------- | --------------- |<br>| Invariant     | none           | `T`           | no substitution |<br>| Covariant     | `out`          | `? extends T` | safe reading    |<br>| Contravariant | `in`           | `? super T`   | safe writing    |</pre><p>Understanding variance based on <strong>data direction</strong> (produce vs consume) — rather than immediately jumping into language syntax — makes it far easier to predict whether a given assignment will compile or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7e974ffd854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines Internals — Part 4]]></title>
            <link>https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-4-36019f6c3817?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/36019f6c3817</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-02-17T03:31:01.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cancellation, Exception Propagation, and Structured Concurrency</h3><p>In the earlier parts of this series, we explored how <a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-1-580c304fd2ba">suspend functions are compiled into state machines</a>, how <a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-2-dc436efd22bb">Continuation</a> works, and how <a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-3-3d0ebdc85772">dispatchers</a> decide where coroutines execute.</p><p>In this final part, we’ll dive into the most misunderstood area of Kotlin coroutines:<br><strong>cancellation, exception propagation, and the real meaning of structured concurrency.</strong></p><p>These topics are often explained with rules, but rarely with the <em>why</em> behind them. Understanding the internals makes coroutine behavior predictable instead of surprising.</p><h3>Cancellation Is Cooperative</h3><p>Coroutines cannot be force-stopped.</p><p>Cancellation in Kotlin is <strong>cooperative</strong>:</p><ul><li>A coroutine’s Job is marked as cancelled</li><li>Cancellation propagates through the job hierarchy</li><li>Suspension points check cancellation and react</li></ul><p>This is why CPU-bound loops that never suspend ignore cancellation unless you check explicitly:</p><pre>ensureActive()<br>// or<br>yield()</pre><p>Suspending functions such as delay, withContext, join, and await automatically perform cancellation checks and throw CancellationException.</p><h3>Why CancellationException Is Special</h3><p>CancellationException does <strong>not</strong> represent failure.</p><p>Internally:</p><ul><li>It signals <em>normal termination</em></li><li>It does not cancel parents</li><li>It is ignored by CoroutineExceptionHandler</li></ul><p>If cancellation behaved like a normal exception, cancelling one child would crash entire coroutine trees. Kotlin coroutines explicitly separate <strong>cancellation</strong> from <strong>failure</strong>.</p><h3>The Job Hierarchy</h3><p>Every coroutine has a Job, and jobs form a <strong>tree</strong>.</p><p>Rules:</p><ul><li>Cancelling a parent cancels all children</li><li>A child failure normally cancels the parent</li><li>A cancelled child does not fail the parent</li></ul><p>This hierarchy is the foundation of structured concurrency:<br>no orphan coroutines and no silent background work.</p><h3>launch: Immediate Failure Propagation</h3><pre>launch {<br>    fail()<br>}</pre><p>Behavior:</p><ul><li>Exception is thrown immediately</li><li>Parent job is cancelled</li><li>Siblings are cancelled</li><li>CoroutineExceptionHandler is invoked</li></ul><p>launch <strong>owns its failures</strong>.<br>It is designed for fire-and-forget work where failure is terminal.</p><h3>async: Deferred Failure Ownership</h3><pre>val d = async {<br>    fail()<br>}</pre><p>Behavior:</p><ul><li>Exception is captured</li><li>Stored inside Deferred</li><li>No cancellation occurs</li><li>Nothing is thrown yet</li></ul><p>Failure is <strong>deferred</strong> until the result is requested:</p><pre>d.await() // exception thrown here</pre><p>At this point:</p><ul><li>Exception is re-thrown in the caller</li><li>Normal Kotlin exception rules apply</li><li>The parent is not cancelled — the scope fails by propagation</li><li>CoroutineExceptionHandler is <strong>NOT</strong> invoked</li></ul><p>Why?</p><ul><li>The exception is considered <strong>handled by the caller</strong> (even if not caught)</li><li>async is a <em>value-producing</em> coroutine</li><li>Failures are delivered via await(), not via handlers</li></ul><p>async transfers <strong>ownership of failure</strong> to the caller.</p><h3>async Without await: Silent by Design</h3><pre>async { fail() }</pre><ul><li>No crash</li><li>No cancellation</li><li>Failure is lost</li></ul><p>This is not a coroutine bug.<br>It is a contract violation: async must always be awaited.</p><p>If you don’t need a result, launch is the correct primitive.</p><h3>Why async Does Not Cancel the Parent</h3><p>Even when await() is called and the exception is uncaught:</p><pre>coroutineScope {<br>    val d = async { fail() }<br>    d.await()<br>}</pre><ul><li>The parent is <strong>not cancelled</strong></li><li>The exception propagates normally</li><li>The scope exits due to failure, not cancellation</li></ul><p>This distinction matters:</p><ul><li>launch cancels the parent</li><li>async throws into the parent</li></ul><h3>supervisorScope: Isolating Cancellation</h3><p>supervisorScope changes <strong>cancellation propagation</strong>, not exception behavior.</p><p>Internally, it uses a SupervisorJob, which breaks the link between child failure and parent cancellation.</p><h3>launch Inside supervisorScope</h3><pre>supervisorScope {<br>    launch { fail() }<br>    launch { work() }<br>}</pre><p>Behavior:</p><ul><li>Failed child does not cancel siblings</li><li>Exception is immediately reported</li><li>Parent is not cancelled</li></ul><p>This is ideal for independent tasks where failures should be visible but isolated.</p><h3>async Inside supervisorScope</h3><pre>supervisorScope {<br>    val d = async { fail() }<br>    d.await()<br>}</pre><p>Behavior:</p><ul><li>Failure is captured</li><li>No cancellation occurs</li><li>Exception is thrown at await()</li><li>Code after await() does not run unless caught</li></ul><p>If await() is never called:</p><ul><li>Failure is silently ignored</li><li>supervisorScope does not help</li></ul><p>supervisorScope does <strong>not</strong> make async safer.</p><h3>CoroutineExceptionHandler: Last-Resort Visibility</h3><p>CoroutineExceptionHandler:</p><ul><li>Handles uncaught exceptions</li><li>Works only with launch</li><li>Never sees CancellationException</li><li>Never sees async failures unless rethrown outside await()</li></ul><p>It is not a replacement for try/catch.<br>It is a safety net for crashes.</p><h3>Final Rules to Remember</h3><ul><li>Use launch for side effects</li><li>Use async for values</li><li>Always await() async</li><li>Never rely on supervisorScope to surface failures</li><li>Cancellation and failure are not the same thing</li></ul><h3>Closing Thoughts</h3><p>Coroutines are often described as “simpler async.”<br>Internally, they are not simpler — they are <strong>stricter</strong>.</p><p>That strictness enforces:</p><ul><li>Bounded lifetimes</li><li>Explicit failure ownership</li><li>Predictable cancellation</li></ul><p>Once you understand these internals, coroutine behavior stops being magical and becomes completely deterministic.</p><p>This concludes the <strong>Kotlin Coroutines Internals</strong> series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36019f6c3817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines Internals — Part 3]]></title>
            <link>https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-3-3d0ebdc85772?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0ebdc85772</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-02-18T07:07:32.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dispatchers, Threading, and Suspension Mechanics</h3><p>In <a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-1-580c304fd2ba">Part 1</a>, we looked at how coroutines work internally using compiler-generated state machines and continuations.</p><p>In <a href="https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-2-dc436efd22bb?postPublishedType=repub">Part 2</a>, we explored how CoroutineContext and Job enforce lifecycle and structured concurrency.</p><p>Now we move to the execution layer.</p><p>In this part, we’ll answer a deceptively simple question:</p><blockquote><em>Where does a coroutine actually run, and how does suspension avoid blocking threads?</em></blockquote><p>To answer this, we need to understand <strong>dispatchers</strong>, <strong>thread usage</strong>, and the mechanics of <strong>suspension and resumption</strong>.</p><h3>Coroutine execution is dispatcher-driven</h3><p>A coroutine does not decide which thread it runs on. That responsibility belongs to the CoroutineDispatcher present in its context.</p><p>A dispatcher determines:</p><ul><li>Which thread (or thread pool) executes the coroutine</li><li>Where the coroutine resumes after suspension</li></ul><p>This is why coroutines are often described as <em>thread-agnostic</em>. A coroutine may start on one thread and resume on another, depending on the dispatcher.</p><h3>Common dispatchers and their intent</h3><p>Kotlin provides several built-in dispatchers, each with a specific purpose:</p><ul><li>Dispatchers.Main – executes coroutines on the main (UI) thread</li><li>Dispatchers.IO – optimized for blocking IO operations</li><li>Dispatchers.Default – optimized for CPU-bound work</li><li>Dispatchers.Unconfined – executes immediately in the caller thread, then resumes in the thread chosen by the suspending function</li></ul><p>The key point is intent, not implementation details. Choosing the correct dispatcher is about <strong>what kind of work</strong> you are doing, not about manually managing threads.</p><h3>Dispatchers and thread pools</h3><p>Internally, most dispatchers are backed by thread pools.</p><ul><li>Dispatchers.Default uses a shared pool sized based on available CPU cores</li><li>Dispatchers.IO uses a larger pool designed to tolerate blocking calls</li></ul><p>Coroutines themselves do not create threads. They reuse threads from these pools and rely on <strong>cooperative scheduling</strong> rather than preemption.</p><p>This is why coroutines scale well: threads are limited, coroutines are not.</p><h3>Thread switching is explicit</h3><p>Thread switching in coroutines does not happen automatically.</p><p>A coroutine changes threads only when:</p><ul><li>It suspends and resumes on a different dispatcher</li><li>withContext is used to switch dispatchers explicitly</li></ul><p>Example:</p><pre>withContext(Dispatchers.IO) {<br>    loadFromDisk()<br>}</pre><p>Here, the coroutine suspends, schedules work on an IO thread, and later resumes back in the original context.</p><h3>How suspension actually works</h3><p>Suspension is the defining feature of coroutines.</p><p>When a coroutine reaches a suspension point:</p><ul><li>The current thread is released</li><li>The continuation is stored by the suspending function</li><li>Execution returns to the dispatcher</li></ul><p>Later, when the suspending operation completes, the continuation is resumed on the appropriate dispatcher.</p><p>From the caller’s perspective, execution appears sequential. Internally, the coroutine has paused and resumed without blocking a thread.</p><h3>delay vs Thread.sleep</h3><p>Consider the difference between these two calls:</p><pre>delay(1000)</pre><pre>Thread.sleep(1000)</pre><p>delay:</p><ul><li>Does not block the thread</li><li>Registers the continuation with a scheduler</li><li>Resumes the coroutine after the delay</li></ul><p>Thread.sleep:</p><ul><li>Blocks the thread</li><li>Prevents other coroutines from running</li><li>Breaks cooperative scheduling</li></ul><p>This distinction is critical. Coroutines remain lightweight only as long as suspension is non-blocking.</p><h3>Suspension points define responsiveness</h3><p>A coroutine can be cancelled or rescheduled only at <strong>suspension points</strong>.</p><p>If a coroutine performs long-running work without suspending:</p><ul><li>Cancellation is delayed</li><li>Other coroutines may starve</li><li>Threads remain occupied</li></ul><p>This is why CPU-bound loops must either:</p><ul><li>Use Dispatchers.Default, or</li><li>Periodically call yield() or ensureActive()</li></ul><h3>The role of withContext</h3><p>withContext is often misunderstood as just a dispatcher switch.</p><p>Internally, it:</p><ul><li>Suspends the current coroutine</li><li>Creates a new context (possibly with a different dispatcher)</li><li>Executes the block</li><li>Restores the original context on completion</li></ul><p>This makes withContext a structured and safe way to perform context switches without losing cancellation or exception semantics.</p><h3>Why Dispatchers.Unconfined is dangerous</h3><p>Dispatchers.Unconfined executes the coroutine immediately in the current thread until the first suspension.</p><p>After suspension, it resumes in whatever thread the suspending function chooses. This makes execution order and threading unpredictable.</p><p>Because of this, Unconfined is generally unsuitable for production code and should be used only for very specific low-level scenarios.</p><h3>Mental model recap</h3><p>At runtime:</p><ul><li>Dispatchers decide where coroutines run</li><li>Suspension releases threads instead of blocking them</li><li>Continuations capture state and resume execution</li><li>Thread switching happens only at suspension boundaries</li></ul><p>Coroutines are lightweight because <strong>threads are treated as a shared resource</strong>, not something owned by a single unit of work.</p><h3>What’s next</h3><p>At this point, we understand:</p><ul><li>How coroutines work internally</li><li>How their lifecycle is enforced</li><li>How execution and suspension are handled</li></ul><p>The final missing piece is <strong>failure and cancellation behavior</strong>.</p><p>In <strong>Part 4</strong>, we’ll dive into <strong>cancellation, exception propagation, and why </strong><strong>launch and </strong><strong>async behave so differently</strong>.</p><p><em>Part 4: </em><a href="https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-4-36019f6c3817"><em>Cancellation and Exception Handling Internals</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0ebdc85772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines Internals — Part 2]]></title>
            <link>https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-2-dc436efd22bb?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc436efd22bb</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-02-11T04:46:33.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines Internals — Part 2</h3><h3>CoroutineContext, Job Hierarchy, and Structured Concurrency</h3><p>In <a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-1-580c304fd2ba">Part 1</a> of this series, we looked at how a <strong>single coroutine</strong> works internally: suspend, continuations, and the compiler-generated state machine.</p><p>But a coroutine never exists in isolation.</p><p>Every coroutine is launched inside a <strong>context</strong>, has a <strong>lifecycle</strong>, and participates in a <strong>hierarchy</strong>. These rules are not conventions — they are enforced by design. This is what gives Kotlin coroutines their safety guarantees.</p><p>In Part 2, we’ll focus on the internals of:</p><ul><li>CoroutineContext</li><li>Job and job hierarchy</li><li>Structured concurrency</li></ul><h3>CoroutineContext: more than just a parameter</h3><p>Every coroutine runs with a CoroutineContext.</p><p>At a high level, it looks like a simple container for configuration. Internally, it is a <strong>persistent, immutable data structure</strong> that behaves like a type-safe map.</p><p>Each element in the context is identified by a unique Key:</p><pre>interface CoroutineContext {<br>    operator fun &lt;E : Element&gt; get(key: Key&lt;E&gt;): E?<br>}</pre><p>Common context elements include:</p><ul><li>Job</li><li>CoroutineDispatcher</li><li>CoroutineName</li><li>CoroutineExceptionHandler</li></ul><p>This design leads to a crucial rule:</p><blockquote><strong><em>A coroutine context can contain exactly one </em></strong><strong><em>Job.</em></strong></blockquote><p>This is intentional. The Job represents the coroutine’s <strong>lifecycle owner</strong>—it controls cancellation and failure propagation. Allowing multiple jobs would make lifecycle rules ambiguous. Enforcing a single job ensures that every coroutine has <strong>one clear owner and one lifecycle</strong>, which is what makes structured concurrency possible.</p><h3>Context combination and propagation</h3><p>Contexts are combined using the + operator:</p><pre>val context = Dispatchers.IO + Job() + CoroutineName(&quot;worker&quot;)</pre><p>Internally:</p><ul><li>The right-hand side replaces elements with the same key</li><li>A new context instance is created (contexts are immutable)</li></ul><p>When a coroutine suspends, its entire context is stored inside the continuation. When it resumes, the same context is restored automatically.</p><p>This is how cancellation, dispatching, and exception handling continue to work <em>across suspension points</em>.</p><h3>Job: the lifecycle controller</h3><p>A Job represents the lifecycle of a coroutine.</p><p>Internally, a job tracks:</p><ul><li>Active state</li><li>Completion</li><li>Cancellation</li><li>Failure cause</li></ul><p>A coroutine transitions through states such as:</p><pre>New → Active → Completing → Completed<br>          ↘ Cancelled</pre><p>Jobs are lightweight and exist purely to coordinate coroutine execution.</p><h3>Parent–child job hierarchy</h3><p>Jobs are arranged in a <strong>tree structure</strong>.</p><pre>Parent Job<br> ├── Child Job 1<br> └── Child Job 2</pre><p>This hierarchy is created automatically when you launch coroutines inside a scope.</p><p>Rules enforced by the hierarchy:</p><ul><li>Cancelling a parent cancels all children</li><li>A parent waits for all children to complete</li><li>Failure of a child cancels the parent (by default)</li></ul><p>This is the foundation of structured concurrency.</p><h3>Structured concurrency: a design constraint</h3><p>Structured concurrency means:</p><blockquote><em>The lifetime of a coroutine is bound to the lifetime of its scope.</em></blockquote><p>This prevents:</p><ul><li>Background work leaking past screens</li><li>Fire-and-forget tasks that never complete</li><li>Silent failures in detached coroutines</li></ul><p>Unlike some concurrency models, Kotlin does not rely on discipline or convention here. The <strong>Job hierarchy enforces it at runtime</strong>.</p><h3>Cancellation propagation</h3><p>Cancellation flows <strong>downward</strong> through the job hierarchy.</p><p>When a job is cancelled:</p><ul><li>All child jobs receive a cancellation signal</li><li>Suspension points throw CancellationException</li><li>Cooperative cancellation checks fail</li></ul><p>Cancellation does not forcibly stop execution. It relies on suspension points and explicit checks.</p><h3>Failure propagation</h3><p>Failure propagation flows <strong>upward</strong>.</p><p>By default:</p><ul><li>A child coroutine failure cancels the parent</li><li>The parent then cancels all other children</li></ul><p>This behavior ensures that a scope does not silently continue in a partially failed state.</p><p>This is also why a single uncaught exception can cancel an entire scope.</p><h3>SupervisorJob and supervision</h3><p>SupervisorJob modifies failure propagation rules.</p><p>With supervision:</p><ul><li>Child failure does <strong>not</strong> cancel the parent</li><li>Other children continue executing</li></ul><p>What does <em>not</em> change:</p><ul><li>The failed child is still cancelled</li><li>The exception still exists</li><li>You must still handle the error</li></ul><p>Supervision isolates failures — it does not ignore them.</p><h3>Why GlobalScope breaks the model</h3><p>GlobalScope creates a coroutine with no parent job.</p><p>Internally, this means:</p><ul><li>No lifecycle ownership</li><li>No structured cancellation</li><li>No automatic waiting</li></ul><p>This is why GlobalScope easily causes memory leaks and orphaned work. It opts out of the very guarantees coroutines are designed to provide.</p><h3>Mental model recap</h3><p>At runtime:</p><ul><li>CoroutineContext carries configuration and control</li><li>Job enforces lifecycle rules</li><li>Parent–child relationships enforce structure</li></ul><p>Coroutines are safe not because developers are careful, but because the model makes unsafe behavior hard.</p><h3>What’s next</h3><p>We now know <strong>how coroutines work</strong> and <strong>who owns them</strong>.</p><p>The next question is:</p><blockquote><em>Where do coroutines actually run, and how does suspension avoid blocking threads?</em></blockquote><p>In <strong>Part 3</strong>, we’ll dive into <strong>Dispatchers, thread pools, and suspension mechanics</strong>.</p><p><em>Part 3: </em><a href="https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-3-3d0ebdc85772"><em>Dispatchers, Threading, and Suspension</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc436efd22bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines Internals — Part 1]]></title>
            <link>https://jyotibhambhu.medium.com/kotlin-coroutines-internals-part-1-580c304fd2ba?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/580c304fd2ba</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 10:56:51 GMT</pubDate>
            <atom:updated>2026-02-09T06:23:05.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines Internals — Part 1</h3><h3>suspend, Continuation, and the State Machine</h3><p>Most developers use Kotlin coroutines every day. We write launch, async, and withContext, and things mostly work. But when something goes wrong—missing logs, silent crashes, cancelled work, or strange threading behavior—many developers realize they don’t actually know how coroutines work internally.</p><p>This series is about building that understanding from first principles.</p><p>In <strong>Part 1</strong>, we’ll answer the most fundamental question:</p><blockquote><em>What actually happens when a coroutine suspends?</em></blockquote><p>To do that, we’ll break down suspend, continuations, and the compiler-generated state machine.</p><p>To do that, we’ll break down three core concepts:</p><ul><li>What a coroutine really is</li><li>What the suspend keyword actually means</li><li>How the compiler turns suspend functions into a state machine</li></ul><h3>What is a coroutine (really)?</h3><p>Before talking about suspend, we need to clarify what a <em>coroutine</em> actually is.</p><p>A coroutine is <strong>not a function</strong> and <strong>not a block of code</strong>.</p><p>A coroutine is:</p><ul><li>A <strong>running instance of a suspendable computation</strong></li><li>Backed by a Continuation</li><li>Executed according to a CoroutineContext</li></ul><p>You can write many suspend functions, but <strong>no coroutine exists</strong> until one is <em>started</em> by a coroutine builder such as launch, async, or runBlocking.</p><pre>suspend fun fetchUser() {<br> // This is NOT a coroutine<br>}</pre><pre>launch {<br> fetchUser() // A coroutine is created here<br>}</pre><p>The distinction matters:</p><ul><li>suspend defines <strong>where suspension is allowed</strong></li><li>Coroutine builders define <strong>when and how execution begins</strong></li></ul><p>This difference becomes critical when we later talk about cancellation, job hierarchies, and structured concurrency.</p><h3>Coroutines are not threads</h3><p>The most common misconception is that coroutines are lightweight threads. They are not.</p><p>A <strong>thread</strong>:</p><ul><li>Is managed by the OS</li><li>Has its own call stack</li><li>Is expensive to create and switch</li></ul><p>A <strong>coroutine</strong>:</p><ul><li>Is a language-level abstraction</li><li>Runs on top of threads</li><li>Does not have its own stack</li></ul><p>Multiple coroutines can run on the same thread, and a single coroutine can resume on different threads during its lifetime. This is possible because coroutines do <strong>not</strong> rely on the thread stack to store execution state.</p><h3>What the suspend keyword really means</h3><p>The suspend keyword does <strong>not</strong> make a function asynchronous.</p><p>It simply means:</p><blockquote><em>This function is allowed to suspend without blocking the thread.</em></blockquote><p>Consider this function:</p><pre>suspend fun fetchUser(): User</pre><p>At the bytecode level, this function cannot suspend by itself. Instead, the Kotlin compiler <strong>rewrites</strong> it.</p><p>Conceptually, it becomes something like this:</p><pre>fun fetchUser(continuation: Continuation&lt;User&gt;): Any</pre><p>Three important things happen here:</p><ol><li>A hidden Continuation parameter is added</li><li>The return type changes from User to Any</li><li>The function may return a special value: COROUTINE_SUSPENDED</li></ol><p>This transformation is the foundation of coroutine internals.</p><h3>Why does the return type become Any?</h3><p>A suspending function has two possible behaviors:</p><ul><li>It completes immediately and returns a value</li><li>It suspends and returns COROUTINE_SUSPENDED</li></ul><p>Because of this dual behavior, the compiler cannot use User as the return type. Instead, it uses Any and lets the runtime decide what happens next.</p><p>If COROUTINE_SUSPENDED is returned, the caller knows:</p><blockquote><em>“This coroutine will resume later using the provided continuation.”</em></blockquote><h3>Continuation: the heart of coroutines</h3><p>A Continuation&lt;T&gt; represents <strong>what should happen next</strong> after a suspension point.</p><p>Internally, a continuation holds:</p><ul><li>The current execution state</li><li>Local variables that must survive suspension</li><li>The CoroutineContext</li><li>The result or exception</li></ul><p>When a coroutine suspends, its continuation is stored somewhere (for example, by delay, an IO dispatcher, or another suspending API). When the operation completes, the continuation is resumed:</p><pre>continuation.resume(value)<br>// or<br>continuation.resumeWithException(error)</pre><p>From the developer’s perspective, the function “continues from where it left off.” Internally, the coroutine is reconstructed from the continuation state.</p><h3>The compiler-generated state machine</h3><p>Every suspending function is compiled into a <strong>state machine</strong>.</p><p>Consider this code:</p><pre>suspend fun loadData() {<br>    val user = fetchUser()<br>    val posts = fetchPosts(user)<br>    show(posts)<br>}</pre><p>The compiler transforms it roughly into:</p><ul><li>A continuation class</li><li>A label field tracking the current state</li><li>Saved local variables as fields</li></ul><p>Execution flow becomes:</p><pre>state 0 -&gt; fetchUser()<br>state 1 -&gt; fetchPosts(user)<br>state 2 -&gt; show(posts)</pre><p>When fetchUser() suspends:</p><ul><li>The current state is saved (label = 1)</li><li>Local variables are stored</li><li>Control returns to the caller</li></ul><p>When resumed, execution jumps directly to state 1, skipping everything before it.</p><p>This is how coroutines resume <strong>without</strong> using the thread stack.</p><h3>Suspension points and labels</h3><p>Not every line in a suspending function becomes part of the state machine.</p><p>A <strong>suspension point</strong> is created <strong>only</strong> when a suspending function is called.</p><pre>suspend fun loadData() {<br>    log(&quot;start&quot;)          // no suspension point<br>    val user = fetchUser() // suspension point<br>    log(&quot;after user&quot;)     // no suspension point<br>    delay(1000)           // suspension point<br>    show(user)<br>}</pre><p>For each suspension point, the compiler assigns a <strong>label</strong> — an integer that represents the point from which execution should resume.</p><p>Conceptually, the function becomes:</p><pre>when (label) {<br>    0 -&gt; { log(&quot;start&quot;); fetchUser() }<br>    1 -&gt; { log(&quot;after user&quot;); delay(1000) }<br>    2 -&gt; { show(user) }<br>}</pre><p>When a suspending call cannot complete immediately:</p><ul><li>The current label is saved</li><li>Local variables are stored in the continuation</li><li>The function returns COROUTINE_SUSPENDED</li></ul><p>When the coroutine is resumed, execution jumps directly to the matching label, skipping all previously executed code.</p><p>Labels are how coroutines resume <strong>without relying on the thread stack</strong>.</p><h3>Why coroutines are cheap</h3><p>Coroutines are cheap because:</p><ul><li>There is no per-coroutine thread stack</li><li>State is stored in small heap objects</li><li>Threads are reused via dispatchers</li><li>Scheduling is cooperative</li></ul><p>This allows tens or even hundreds of thousands of coroutines to exist simultaneously — something impossible with threads alone.</p><h3>Common misconceptions clarified</h3><ul><li>suspend makes code asynchronous</li><li>Suspending blocks the thread</li><li>Coroutines preserve the call stack</li></ul><p>What actually happens is explicit state saving and restoration via continuations.</p><h3>What’s next</h3><p>Now that we understand how a <strong>single coroutine</strong> works internally, the next question is:</p><blockquote><em>Who owns the coroutine and controls its lifetime?</em></blockquote><p>In <strong>Part 2</strong>, we’ll dive into <strong>CoroutineContext, Job hierarchy, and structured concurrency</strong> — the design that prevents leaks and enforces correctness.</p><p><a href="https://medium.com/@jyotibhambhu/kotlin-coroutines-internals-part-2-dc436efd22bb"><em>Part 2: CoroutineContext, Job, and Structured Concurrency</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580c304fd2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Reliable and Resilient S3 Multipart Upload System for Android]]></title>
            <link>https://jyotibhambhu.medium.com/building-a-reliable-and-resilient-s3-multipart-upload-system-for-android-944f634e83e6?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/944f634e83e6</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 07:36:13 GMT</pubDate>
            <atom:updated>2025-11-03T04:52:18.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yq0Wjcif4mQxUVEF" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Uploading large media files is straightforward in theory but complex in practice. Unstable networks, app restarts, and Android’s background restrictions can easily disrupt uploads. A robust system must be able to recover gracefully, retry intelligently, and persist progress without user intervention.</p><p>While AWS provides multipart upload functionality through its SDKs, I built a <strong>custom implementation</strong> specifically for Android. The motivation was threefold — <strong>reduce app size</strong>, <strong>gain full control over concurrency and retries</strong>, and <strong>align better with coroutine-based architecture and WorkManager</strong>.</p><p>This post walks through the architecture, metadata model, concurrency strategy, and resilience mechanisms behind that system.</p><h3>Why Multipart Upload</h3><p>Multipart upload enables large files to be split into smaller parts, uploaded independently, and then reassembled by Amazon S3 once all parts complete successfully.</p><p>This approach offers several benefits:</p><ul><li><strong>Parallelism:</strong> upload multiple parts concurrently for higher throughput</li><li><strong>Fault isolation:</strong> retry only failed parts instead of restarting the full upload</li><li><strong>Continuity:</strong> resume from the last known state after interruption</li></ul><p>For mobile clients, these features are essential. Network quality fluctuates constantly, and uploads need to survive beyond a single session or process lifetime.</p><h3>Architecture Overview</h3><p>The system is built around three primary layers:</p><ol><li><strong>Framework layer</strong> — responsible for scheduling and executing background uploads using WorkManager.</li><li><strong>Domain layer</strong> — coordinates multipart upload logic through a set of use cases.</li><li><strong>Data layer</strong> — persists metadata locally and interacts with backend APIs for presigned URLs and upload completion.</li></ol><p>A typical flow looks like this:</p><pre>UploadScheduler → S3UploadWorker → S3UploadManager<br>                           ↓<br>              MultipartUploadOrchestratorUseCase<br>                           ↓<br>          UploadMetadataStorageRepo + UploadRepository<br>                           ↓<br>           Local Storage     ←→     S3 / Backend APIs</pre><p>Each layer has a single responsibility and communicates through well-defined contracts.</p><p>For more detailed implementation, please refer this <a href="https://www.mermaidchart.com/play#pako:eNq1V11P4zoQ_SvePqBUCvuhu08Vi3RvCFK1UFBLxQvSyiTT1sKxc21noVrtf99xnKTOBwth7-WBlmTmeM7MmfHwY5LIFCaziYZ_CxAJnDG6VTS7EwR_cqoMS1hOhSERZyBM__k655Kmq2QHacFB9Q1upXq4pIJuh146b2vy_NsXnK8Unq2NokYO2JxRQy_ofsj9WsmtAq0bfGfiiB6fnnaYzYiuvl4W3DCL5CyCovyYpyHZMA7X1OxCsqN69xX2IaF5LpkwGWJaC4V5ZnhqtKNqy8T28OSWbdi0DmIhDRD5HRTpRbECU-QkksJyRmRNjsocL20FdVWhjtcQm0gBxUM8oNnJvfpwekwWYB4R8Gafw_v14jK-iZfx2YfoarGIo5v4rLJaVnH_Q40BtceIL-RjYFQB045FzTWQuWFSUF4bxE-5FJgYRjm5p8mD3GxCktGnJRjFQH_59PE5Np6oZgQEMi9gLRh-2jfB3cTV5FtdmrtJSL7G8XVIikZx02FwRHcSmCEBUyhBrnJAdWHk_eq04rilzJCNVCTximMkuQeSQVUYz6EpipP_jKSyDH5KHpnZEVWIvzGzWW4iWYhWXZ1D498E4LgFyimhxa97pt81M4IEMe5sCbrIYN1F8XF8PwRr2mtGtlD1wyUYmuLzGmGeVpE0xsfPhOGfPxcbWR9Ned3sRACkdVJRWga7EFJnNdQ3bfxIZjkHtKjAzrl8PPgOEuwMCRRbxkz8HeWBIot2hXhAYZd9fzeZvoDlJSuxnufoFdQjw3N-MU_WsTzbptpa14l6G425YNiCxhJxChpFhTnvWjadeWfpLWgGIdbMUH6N9dJjqM5b6K4zcmTCtgJSsl5e6D_j7jwsdTvQdYs5lzIn59jPQJOdKxkJ0IxyDtyze02WXGIt_aAECg8s1qoLZvW-KpIEg26_eFXKapWXp7X9gWsgnz_-ZVndszQF8Tv8FoEULOYLHT4qzlip-sZu4hNeL5d__FF7ukS8UddJlcZK11n70rfaTvxEj1J11MJ2qradglKoKZelqt4nVFTzDsdj-noKOJKXkOE9hCko54U-VOywrIwJvA13GD_j2qBBKROHMbViHBPPBdPmpCX40_-ywtjp0f9T5I7AvRtO28bHS-7tynf2TeC_13x_i7C3MDfvtRtAQRVyD6XeKHprTMe_51htL90tbtjNb4MNZXx0WoocJxWsDP4KzhEA0gDs4AltV9lFcz99Y4JsOIUCBzc6PV3vg7_VQoQdr2xwJOjsgeTE25DJ0RF5t4KkUMzs46cEygV78GpqdsahpJdHBR2_Z7bcelOu4itlDf1F3pvjtoRISEjjfEaHV-dq2rkcOk3Uqb2_yVdLvlVBpQj7b1PZLnry8xesRyup">sequence diagram</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYtp5EnZth0BC_NGdJnCKQ.png" /></figure><h3>Multipart Upload Orchestration</h3><p>The upload orchestration follows these key steps:</p><ol><li><strong>Initiate</strong> the multipart upload by fetching presigned URLs and an uploadId from the backend.</li><li><strong>Chunk</strong> the file into multiple parts (typically 5–10 MB each).</li><li><strong>Upload</strong> parts concurrently while respecting the concurrency cap.</li><li><strong>Update</strong> progress and metadata after each part.</li><li><strong>Complete</strong> the upload once all parts have successfully uploaded.</li></ol><p>Each of these steps is isolated in a use case within the domain layer, allowing individual testing and reuse.</p><h3>Controlled Concurrency with Coroutines</h3><p>Concurrency is managed using Kotlin coroutines. To prevent resource exhaustion, parallel uploads are limited to a fixed number of parts — in this case, five.<br> Using supervisorScope ensures that one failing coroutine doesn’t cancel others:</p><pre>suspend fun uploadParts(parts: List&lt;FilePart&gt;) = supervisorScope {<br>    val semaphore = Semaphore(5) // Limit parallel uploads to 5</pre><pre>    parts.map { part -&gt;<br>        async {<br>            semaphore.withPermit {<br>                uploadPartUseCase.execute(part)<br>                updateProgress(part)<br>                persistMetadata()<br>            }<br>        }<br>    }.awaitAll()<br>}</pre><p>This structure keeps uploads efficient yet predictable, ensuring balanced CPU, memory, and network utilization even under heavy workloads.</p><h3>Designing for Resilience</h3><p>Reliability isn’t only about successful uploads — it’s about <strong>recovering predictably when things fail</strong>.</p><p>Resilience in this system is built through multiple layers:</p><h3>1. Persistent State</h3><p>Every part completion triggers a metadata update. Even if the app crashes or the OS kills the worker, the system can reconstruct the upload state from the persisted file.</p><p>This guarantees continuity across sessions.</p><h3>2. Retry and Backoff Policy</h3><p>Each failed part is retried using exponential backoff with a capped retry count.<br> For example:</p><ul><li>Retry 1 after 2 seconds</li><li>Retry 2 after 4 seconds</li><li>Retry 3 after 8 seconds</li><li>Then mark the upload as failed if the limit is reached</li></ul><p>This approach balances network efficiency with user experience, avoiding aggressive retries during connectivity drops.</p><h3>3. SupervisorScope Isolation</h3><p>By using supervisorScope, part failures do not cancel the entire upload. Only the failed parts are retried.<br> This isolation prevents cascading failures and significantly improves overall completion rates.</p><h3>4. Graceful Recovery</h3><p>If WorkManager re-triggers the worker due to constraints (like battery or connectivity), the orchestrator reads the last known UploadMetadata and resumes pending parts.</p><p>Uploads continue seamlessly from the last persisted byte count — without user intervention.</p><h3>5. Cleanup and Expiry</h3><p>A CleanUpUseCase periodically removes stale or incomplete metadata files to prevent storage bloat.<br> Uploads that remain incomplete for a defined window (for example, 7 days) are automatically aborted both locally and on S3.</p><h3>Why Build a Custom Implementation</h3><p>AWS SDKs provide comprehensive multipart upload support, but using them directly in Android apps introduces trade-offs:</p><ul><li><strong>App size impact:</strong> the SDK adds several megabytes due to internal dependencies.</li><li><strong>Limited control:</strong> concurrency and retry policies are opaque and not easily adjustable.</li><li><strong>Integration overhead:</strong> SDK threads and callbacks don’t align well with structured coroutines and WorkManager’s lifecycle.</li></ul><p>By building a custom implementation, I gained:</p><ul><li>Full ownership of upload lifecycle and retry strategy.</li><li>Lightweight footprint with only necessary dependencies.</li><li>Seamless integration with coroutine scopes, structured concurrency, and domain-driven design.</li><li>Fine-grained telemetry and analytics for every part upload.</li></ul><p>This control proved invaluable in maintaining predictable, observable, and maintainable behavior.</p><h3>Best Practices and Lessons Learned</h3><ol><li><strong>Persist often</strong> — update metadata after every successful part.</li><li><strong>Keep parallelism bounded</strong> — uncontrolled concurrency can degrade mobile performance.</li><li><strong>Design for restarts</strong> — assume the process can die at any point.</li><li><strong>Use structured concurrency</strong> — supervisorScope simplifies partial failure recovery.</li><li><strong>Separate orchestration from transport</strong> — treat API calls as plug-ins to the orchestration layer.</li><li><strong>Measure and tune</strong> — monitor completion rates, retry counts, and average part size continuously.</li></ol><h3>Conclusion</h3><p>A resilient multipart upload system is not just about faster uploads — it’s about ensuring uploads <strong>always finish</strong>, no matter how unreliable the environment is.</p><p>By designing around persistence, controlled concurrency, and structured error handling, it’s possible to build an Android upload pipeline that performs reliably under real-world conditions — without depending on heavyweight SDKs.</p><p>The final system is small, resilient, and fully autonomous. Uploads run quietly in the background, recover after restarts, and finish consistently — the kind of reliability users never notice, but always expect.</p><pre> ┌────────────────────────────────────────────┐<br> │                WorkManager                 │<br> │  (Schedules / Restarts Upload Worker)      │<br> └────────────────────────────────────────────┘<br>                       │<br>                       ▼<br> ┌────────────────────────────────────────────┐<br> │          MultipartUploadOrchestrator       │<br> │   - Loads UploadMetadata                   │<br> │   - Identifies pending parts               │<br> │   - Spawns parallel upload coroutines      │<br> └────────────────────────────────────────────┘<br>                       │<br>                       ▼<br> ┌────────────────────────────────────────────┐<br> │     UploadPartUseCase (with Retry Policy)  │<br> │   - Uploads part using Presigned URL       │<br> │   - Updates progress + metadata            │<br> │   - Retries failed parts (exponential backoff)<br> └────────────────────────────────────────────┘<br>                       │<br>                       ▼<br> ┌────────────────────────────────────────────┐<br> │           UploadMetadataRepository          │<br> │   - Persists state after each part          │<br> │   - Restores progress after crash/restart   │<br> └────────────────────────────────────────────┘<br>                       │<br>                       ▼<br> ┌────────────────────────────────────────────┐<br> │            CompletionUseCase               │<br> │   - Verifies all parts uploaded            │<br> │   - Finalizes upload with S3               │<br> │   - Cleans up metadata                     │<br> └────────────────────────────────────────────┘</pre><h3>Stay Connected:</h3><p>To stay updated with the latest developments and tutorials, follow me on <a href="https://github.com/JyotiBhambhu">GitHub</a> and <a href="https://jyotibhambhu.medium.com/">Medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=944f634e83e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures Explained: Memory Management in Android, iOS, and React Native]]></title>
            <link>https://jyotibhambhu.medium.com/closures-explained-memory-management-in-android-ios-and-react-native-6d96f03b6f9a?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d96f03b6f9a</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clo]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 05:18:37 GMT</pubDate>
            <atom:updated>2025-08-12T05:18:37.371Z</atom:updated>
            <content:encoded><![CDATA[<p>Closures Explained: Memory Management in Android, iOS, and React Native</p><p>Closures are everywhere in modern programming — from handling button clicks to running asynchronous tasks. But while they are powerful, they also have some hidden details that can cause memory issues if not handled properly.</p><p>This guide breaks down closures in <strong>Android (Kotlin)</strong>, <strong>iOS (Swift)</strong>, and <strong>React Native (JavaScript/TypeScript)</strong>, and shows how memory behaves differently in each platform.</p><h3>What is a Closure?</h3><p>A closure is a function that “remembers” variables from the environment in which it was created, even after that environment is gone.</p><p>Example in plain terms:</p><ul><li>You define a function <strong>inside another function</strong>.</li><li>The inner function uses variables from the outer one.</li><li>The inner function keeps those variables alive as long as it exists.</li></ul><h3>Closures in Each Platform</h3><h3>Android (Kotlin)</h3><p>In Kotlin, lambdas and anonymous functions are closures.<br> They can capture variables from their surrounding scope.</p><pre>val greeting = &quot;Hello&quot;<br>val greeter: (String) -&gt; String = { name -&gt;<br>    &quot;$greeting, $name!&quot;<br>}</pre><p>Closures are heavily used in Android for things like setOnClickListener or coroutines.<br> The JVM garbage collector will eventually clean them up, but you need to avoid keeping references to Activity or Fragment instances in long-lived lambdas, as that can cause memory leaks.</p><h3>iOS (Swift)</h3><p>In Swift, closures look like this:</p><pre>let greeter = { (name: String) -&gt; String in<br>    &quot;Hello, \(name)!&quot;<br>}</pre><p>Swift captures variables <strong>strongly by default</strong>, which can create <strong>retain cycles</strong> if you’re not careful. This happens when:</p><ul><li>A class instance has a closure property.</li><li>That closure captures self strongly.</li><li>Both keep each other alive forever.</li></ul><p>To prevent this, use <strong>capture lists</strong>:</p><pre>{ [weak self] in<br>    self?.doSomething()<br>}</pre><h3>React Native (JavaScript/TypeScript)</h3><p>In JavaScript, functions are closures by default:</p><pre>function makeGreeter(greeting) {<br>  return function(name) {<br>    return `${greeting}, ${name}!`;<br>  };<br>}</pre><p>JavaScript uses garbage collection, so you don’t manage memory manually.<br> However, if you store closures in arrays, maps, or global variables and never clear them, they can still hold on to large data and cause memory bloat.</p><h3>Memory Management Differences</h3><p>Here’s a simple diagram to illustrate how closures capture variables and how memory is handled in each platform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StvgHiTkdkfz6ySfpLWoEA.png" /></figure><h3>Best Practices for Each Platform</h3><p><strong>Android (Kotlin)</strong></p><ul><li>Avoid capturing this in long-lived lambdas.</li><li>Use applicationContext instead of Activity where possible.</li></ul><p><strong>iOS (Swift)</strong></p><ul><li>Always use [weak self] in closures stored in properties or async callbacks.</li><li>Use [unowned self] only if you are sure the object will still exist.</li></ul><p><strong>React Native (JavaScript)</strong></p><ul><li>Clear stored closures when they are no longer needed.</li><li>Avoid capturing large data structures unnecessarily.</li></ul><h3>Final Thoughts</h3><p>Closures make code cleaner and more expressive, but understanding how they handle memory is crucial to avoiding performance issues. Each platform has its own quirks:</p><ul><li>Android relies on the JVM garbage collector.</li><li>iOS requires explicit attention to capture semantics.</li><li>React Native depends on JavaScript’s garbage collection.</li></ul><p>If you handle closures with these platform-specific rules in mind, you’ll have cleaner, safer, and more efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d96f03b6f9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit Network Optimization]]></title>
            <link>https://jyotibhambhu.medium.com/retrofit-network-optimization-73d699663617?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d699663617</guid>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 17:28:12 GMT</pubDate>
            <atom:updated>2025-02-28T17:28:12.533Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android, we typically use <strong>Retrofit with OkHttp</strong> for network calls. OkHttp runs on <strong>TCP (Transmission Control Protocol)</strong> and supports <strong>HTTP/2 by default</strong> (on Android 5.0+), provided the server supports it. If the server only supports <strong>HTTP/1</strong>, OkHttp automatically falls back to <strong>HTTP/1.1</strong>.</p><p>You can check which protocol is being used by looking at logs or tools like <strong>Chucker</strong>. If it shows <strong>h2</strong>, it’s HTTP/2; if it shows <strong>h1</strong>, it’s HTTP/1.</p><h3>Why is HTTP/2 faster than HTTP/1?</h3><p>Both use TCP, but HTTP/2 improves speed by:<br>✅ <strong>Multiplexing</strong> — Multiple requests can be sent at the same time without blocking each other.<br>✅ <strong>Header Compression</strong> — Reduces the size of request headers, saving bandwidth.</p><h3>Need even faster responses? Try HTTP/3!</h3><p>While HTTP/2 is great, <strong>HTTP/3</strong> is even faster and works almost in real-time. Instead of <strong>TCP</strong>, it uses <strong>QUIC</strong>, which is built on <strong>UDP (User Datagram Protocol)</strong>.</p><p>🔹 <strong>UDP is faster than TCP</strong>, but it’s usually unreliable (it doesn’t guarantee delivery of all data).<br>🔹 <strong>QUIC fixes this</strong> by adding a retry mechanism and parallel streams, so if one packet fails, only that part is retried — without blocking others.<br>🔹 It also has <strong>built-in security (TLS)</strong>, so no need to add encryption separately.</p><h3>Using HTTP/3 in Retrofit</h3><p>OkHttp <strong>does not</strong> support QUIC directly, but you can use <strong>Cronet</strong> as an interceptor. It’s as simple as adding an extra step in your Retrofit setup.</p><p>For full benefits, you can even use Cronet as the <strong>Call Factory</strong>, replacing OkHttp in your Retrofit builder. This gives you faster, more efficient networking without major code changes. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d699663617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Android App Performance: Retrofit Network Optimization]]></title>
            <link>https://jyotibhambhu.medium.com/improve-android-app-performance-retrofit-network-optimization-0696b732b6fd?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0696b732b6fd</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 12:32:15 GMT</pubDate>
            <atom:updated>2025-03-03T10:37:30.448Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Android development, efficient network communication is crucial for a seamless user experience. While <strong>Retrofit</strong> is the go-to library for making network calls, understanding how different <strong>HTTP versions impact performance</strong> can help you make better architectural decisions.</p><p>This guide explores <strong>HTTP/1.1, HTTP/2, and HTTP/3</strong>, their differences, and how to optimize network calls in <strong>Android using Retrofit and OkHttp</strong>.</p><h3>🚀 Evolution of HTTP Protocols</h3><p>Over the years, <strong>HTTP protocols have evolved</strong> to improve speed, reduce latency, and handle multiple requests efficiently. Here’s how different versions impact network performance.</p><p><strong>Note</strong>: for measuring performance impact I took 1 same api call as a reference.</p><h3>1️⃣ HTTP/1.1: The Traditional Approach</h3><p>HTTP/1.1 was a major improvement over HTTP/1.0, enabling persistent connections and pipelining. However, it still suffered from <a href="https://jyotibhambhu.medium.com/how-http-3-eliminates-head-of-line-hol-blocking-7cad77b8b595"><strong>head-of-line (HOL) blocking</strong></a> and connection overhead.</p><h3>🔹 How It Works</h3><ul><li>Works over <strong>TCP</strong>.</li><li>Each request requires a <strong>separate connection</strong> or <strong>persistent connection reuse</strong>.</li><li><a href="https://jyotibhambhu.medium.com/how-http-3-eliminates-head-of-line-hol-blocking-7cad77b8b595"><strong>Head-of-line (HOL) blocking</strong></a> occurs when a single slow request delays all subsequent ones.</li></ul><h3>⏳ Performance Impact</h3><ul><li><strong>600ms</strong> response time for the first API call.</li><li><strong>200ms</strong> response time for subsequent calls (due to keep-alive and caching).</li></ul><h3>⚙️ Retrofit with HTTP/1.1</h3><p>By default, OkHttp supports HTTP/1.1, but explicitly forcing it ensures compatibility with older devices.</p><pre>val client = OkHttpClient.Builder()<br>    .protocols(listOf(Protocol.HTTP_1_1))<br>    .build()<br><br>val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.example.com&quot;)<br>    .client(client)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><h3>2️⃣ HTTP/2: Faster &amp; More Efficient</h3><p>HTTP/2 was introduced to <strong>fix HTTP/1.1’s limitations</strong> by <strong>multiplexing multiple requests</strong> over a <strong>single connection</strong> and reducing connection overhead.</p><h3>🔹 How It Works</h3><ul><li>Still <strong>works over TCP</strong> but <strong>supports </strong><a href="https://jyotibhambhu.medium.com/how-http-2-fixes-http-1-1-pipelining-issues-6362377f7c3b"><strong>multiplexing</strong></a>.</li><li>Uses <strong>header compression (HPACK)</strong> to reduce redundant data transmission.</li><li><strong>Server push</strong> allows sending resources <strong>before the client requests them</strong>.</li></ul><h3>⏳ Performance Impact</h3><ul><li><strong>200ms</strong> response time for the first API call.</li><li><strong>140ms</strong> response time for subsequent calls (better efficiency with multiplexing).</li></ul><h3>⚙️ Retrofit with HTTP/2</h3><p>OkHttp <strong>enables HTTP/2 by default</strong> (for API 21+). If your server supports HTTP/2, OkHttp will <strong>automatically negotiate the best protocol</strong>.</p><pre>val client = OkHttpClient.Builder()<br>    .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))<br>    .build()</pre><h3>3️⃣ HTTP/3: The Future with QUIC</h3><p>HTTP/3 uses <strong>QUIC (Quick UDP Internet Connections)</strong> instead of TCP, bringing:</p><h3>🔹 How It Works</h3><ul><li>Uses <strong>QUIC</strong>, a transport protocol built on <strong>UDP</strong>.</li><li>Combines <strong>UDP’s low-latency benefits</strong> with <strong>TCP-like reliability</strong>.</li><li>Eliminates <a href="https://jyotibhambhu.medium.com/how-http-3-eliminates-head-of-line-hol-blocking-7cad77b8b595"><strong>head-of-line blocking</strong></a> with independent streams.</li><li>Enables <strong>faster handshakes</strong> and <strong>seamless network switching</strong>, ideal for mobile apps. 🚀</li></ul><h3>⏳ Performance Impact</h3><ul><li><strong>0ms</strong> response time in ideal cases (real-time performance).</li><li><strong>Better stability</strong> on <strong>weak or fluctuating networks</strong>.</li></ul><h3>⚙️ Retrofit with HTTP/3 (via Cronet)</h3><p>Retrofit <strong>doesn’t support QUIC/HTTP/3 directly</strong>, but you can integrate it using <strong>Cronet</strong> in two ways:</p><p>1️⃣ Using Cronet as a Call Factory (Replacing OkHttp)</p><p>📌 <strong>Dependency (app-level </strong><strong>build.gradle)</strong></p><pre>implementation(&quot;org.chromium.net:cronet-embedded:119.6045.31&quot;)</pre><p>📌 <strong>Cronet Retrofit Integration</strong></p><pre><br>val cronetEngine = CronetEngine.Builder(context)<br>      .enableHttp2(true)  // Enable HTTP/2<br>      .enableQuic(true)   // Ensure HTTP/3 (QUIC) is enabled<br>//            .addQuicHint(<br>//                &quot;super-app-backend.qac24svc.dev&quot;,<br>//                443,<br>//                443<br>//            ) // Force QUIC<br>    .build()<br><br>val callFactory = CronetCallFactory.newBuilder(cronetEngine).build()<br><br>val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.example.com&quot;)<br>    .callFactory(callFactory)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><p>📌 <strong>Important:</strong> Ensure your server advertises <strong>alt-svc: h3=&quot;:443&quot;</strong> in response headers to enable HTTP/3.</p><p>2️⃣ Using Cronet as an Interceptor (Alongside OkHttp)</p><p>📌 <strong>Dependencies (app-level </strong><strong>build.gradle)</strong></p><pre>implementation(&quot;org.chromium.net:cronet-embedded:119.6045.31&quot;)<br>implementation(&quot;com.google.net.cronet:cronet-okhttp:0.1.0&quot;)</pre><p>📌 <strong>Integration with OkHttp</strong></p><pre>val cronetEngine = CronetEngine.Builder(context)<br>      .enableHttp2(true)  // Enable HTTP/2<br>      .enableQuic(true)   // Ensure HTTP/3 (QUIC) is enabled<br>      .build()<br><br> val okHttpClient = OkHttpClient.Builder().addInterceptor(CronetInterceptor.newBuilder(cronetEngine).build())<br><br>val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.example.com&quot;)<br>    .client(okHttpClient)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><p>Remember to add this intercepter as last otherwise it will replace others.</p><h3>🔥 Performance Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nrxyplyh2XkQIz0BeHkYw.png" /></figure><p><strong>Best Choice?</strong></p><ul><li>Use <strong>HTTP/2</strong> for most cases</li><li>Use <strong>HTTP/3</strong> if your backend supports QUIC (better performance in weak networks)</li></ul><h3>📌 Final Thoughts</h3><ol><li><strong>HTTP/1.1</strong> is outdated but still in use.</li><li><strong>HTTP/2</strong> is the default in OkHttp and improves speed.</li><li><strong>HTTP/3</strong> (QUIC) is the future but requires extra setup.</li><li><strong>Retrofit + Cronet</strong> is needed for QUIC support in Android.</li></ol><p>🚀 Start optimizing your network calls today and <strong>future-proof your Android app</strong>! 💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0696b732b6fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Evolution of HTTP and Its Impact on Mobile Apps]]></title>
            <link>https://jyotibhambhu.medium.com/evolution-of-http-and-its-impact-on-mobile-apps-7b633ddf3c33?source=rss-8bb3f282f6e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b633ddf3c33</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[retrofit]]></category>
            <dc:creator><![CDATA[Jyoti Sheoran]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 12:02:17 GMT</pubDate>
            <atom:updated>2025-02-26T12:02:17.855Z</atom:updated>
            <content:encoded><![CDATA[<p>As mobile applications rely heavily on network requests, <strong>faster, more efficient communication protocols</strong> directly impact <strong>performance, battery life, and user experience</strong>.</p><p>Let’s explore <strong>the evolution of HTTP</strong>, from its early days to modern <strong>HTTP/3</strong>, and how each version impacts mobile app performance.</p><h3>🔹 HTTP/1.0 — The Beginning (1996)</h3><p><strong>How It Works:</strong><br>HTTP/1.0 was the first widely adopted web protocol. Each request required a <strong>new TCP connection</strong>, leading to <strong>high latency and excessive resource usage</strong>.</p><h4>📉 Impact on Mobile Apps:</h4><p>🚫 <strong>Slow API responses</strong> — Each request starts a new TCP handshake, increasing delays.<br>🚫 <strong>High battery drain</strong> — Frequent connection setups consume more CPU and power.<br>🚫 <strong>Poor mobile network handling</strong> — Struggles with unstable 3G/4G connections.</p><p>💡 <strong>Verdict:</strong> HTTP/1.0 is outdated and unsuitable for modern mobile apps.</p><h3>🔹 HTTP/1.1 — Persistent Connections (1997, Still in Use)</h3><p><strong>How It Works:</strong></p><ul><li>Introduced <strong>persistent connections (Keep-Alive)</strong> — A single TCP connection could be reused for multiple requests.</li><li>Added <strong>pipelining*</strong> (requests can be sent in sequence without waiting for responses).</li></ul><h4>📈 Impact on Mobile Apps:</h4><p>✅ <strong>Reduced network overhead</strong> — Connections stay open longer, reducing handshake time.<br>✅ <strong>Lower battery usage</strong> — Fewer connection setups mean less power consumption.<br>⚠️ <strong>Head-of-Line (HOL) Blocking</strong> — One slow request can block others.<br>⚠️ <strong>Limited parallelism</strong> — Still cannot send multiple requests simultaneously over a single connection.</p><p>💡 <strong>Verdict:</strong> HTTP/1.1 improved efficiency but still suffers from <strong>latency issues</strong>.</p><h3>🔹 HTTP/2 — Multiplexing for Speed (2015)</h3><p><strong>How It Works:</strong></p><ul><li>Introduced <strong>multiplexing</strong> (improvement over pipeline)— multiple requests can share a single TCP connection.</li><li>Uses <strong>HPACK header compression</strong> — reducing redundant data transfer.</li><li>Supports <strong>server push</strong> — preloading resources before they are explicitly requested.</li></ul><h4>📈 Impact on Mobile Apps:</h4><p>✅ <strong>Faster API calls</strong> — Multiple requests execute in parallel over the same connection.<br>✅ <strong>Lower bandwidth usage</strong> — Compressed headers reduce unnecessary data transfer.<br>✅ <strong>Reduced latency</strong> — Avoids TCP slow-start issues.<br>⚠️ <strong>Still uses TCP</strong> — Prone to <strong>congestion and packet loss delays</strong>.</p><p>💡 <strong>Verdict:</strong> HTTP/2 significantly improves performance, making it the default choice for modern mobile apps using <strong>Retrofit + OkHttp</strong>.</p><h3>🔹 HTTP/3 — QUIC and the Future of Mobile Networking (2020+)</h3><p><strong>How It Works:</strong></p><ul><li>Uses <strong>UDP instead of TCP</strong>, avoiding slow handshakes.</li><li>Eliminates <strong>head-of-line blocking</strong> at the transport layer.</li><li>Improves performance over <strong>unstable networks</strong> (e.g., switching between Wi-Fi and 4G).</li></ul><h4>📈 Impact on Mobile Apps:</h4><p>✅ <strong>Ultra-fast API calls</strong> — Eliminates TCP overhead, reducing latency.<br>✅ <strong>Great for weak networks</strong> — Handles packet loss efficiently.<br>✅ <strong>Better battery performance</strong> — Fewer reconnections mean less power consumption.<br>⚠️ <strong>Backend dependency</strong> — Your server must support QUIC.</p><p>💡 <strong>Verdict:</strong> HTTP/3 is the best for mobile apps, especially in poor network conditions. Use <strong>Retrofit + Cronet</strong> for QUIC support.</p><h3>📊 HTTP Evolution Summary for Mobile Apps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsOc0Ke9KXwh7nPHFnFTQQ.png" /></figure><h3>📌 Final Thoughts</h3><p>1️⃣ <strong>Avoid HTTP/1.0 and HTTP/1.1</strong> — Too slow and inefficient.<br>2️⃣ <strong>Use HTTP/2 (default in OkHttp)</strong> — Great for most mobile apps.<br>3️⃣ <strong>Use HTTP/3 (QUIC) for best performance</strong> — Especially useful in unstable network conditions.</p><p>🚀 Start optimizing your network calls today and <strong>future-proof your Android app</strong>! 💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b633ddf3c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>