<?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 Guruprasad Hegde on Medium]]></title>
        <description><![CDATA[Stories by Guruprasad Hegde on Medium]]></description>
        <link>https://medium.com/@guruprasadhegde4?source=rss-3d3f7ac863cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ifS_GZ_v7bPltLLU-OM8tg.jpeg</url>
            <title>Stories by Guruprasad Hegde on Medium</title>
            <link>https://medium.com/@guruprasadhegde4?source=rss-3d3f7ac863cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:20:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guruprasadhegde4/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[Kotlin Flow Cancellation]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-flow-cancellation-b16e50f7c3bf?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16e50f7c3bf</guid>
            <category><![CDATA[koltin]]></category>
            <category><![CDATA[cancellations]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 06:19:29 GMT</pubDate>
            <atom:updated>2025-03-28T06:19:29.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8oqWKTi2rAosctW3JJNUA.png" /></figure><h4>What is Flow Cancellation?</h4><p><strong>Flow Cancellation</strong> means <strong>stopping</strong> or <strong>terminating</strong> a running flow when it is <strong>no longer needed</strong> or when the <strong>coroutine scope is cancelled</strong>.</p><p>Kotlin Flow is <strong>cold &amp; cancellable by default</strong> → When the coroutine collecting it is cancelled, the upstream flow and its operations are also cancelled.</p><p>Think of it like <strong>turning off a water tap</strong> when you don’t need the water (data) anymore.</p><h4>Why is Flow Cancellation important?</h4><p>1.<strong>Resource Management:</strong> Stops long-running/expensive upstream tasks.</p><p>When you collect a Flow, it might be doing:</p><ul><li>Network calls</li><li>Database queries</li><li>Heavy calculations</li></ul><p>If you don’t cancel the flow when it’s no longer needed (like when the user leaves the screen), it will <strong>keep consuming memory, CPU, and battery.</strong><br> Cancellation helps <strong>stop unnecessary work.</strong></p><p>2. <strong>Avoid Memory Leaks: </strong>Stops unnecessary emissions when UI is destroyed.</p><p>If a flow keeps emitting without a collector, it can <strong>hold references</strong> to your Activity/Fragment → leading to <strong>memory leaks</strong>.<br> <strong>Cancellation clears those references.</strong></p><p><strong>3. Lifecycle Safety:</strong> Follows structured concurrency → Automatically cancelled with scope.</p><p>When you launch a Flow inside a <strong>CoroutineScope</strong> (like lifecycleScope, viewModelScope), the Flow is <strong>automatically cancelled</strong> when the scope is cancelled.</p><p>4. Better User Experience:</p><p>When the screen changes, user navigates back, or app is closed → If the flow is still running, it can cause:</p><ul><li><strong>Crashes</strong></li><li><strong>Slow UI</strong></li><li><strong>Unexpected behavior</strong></li></ul><p>Cancellation ensures that flows <strong>stop at the right time</strong> → Smooth experience.</p><h4>How Flow Cancellation Works Internally</h4><p>When you call flow.collect { }, it uses a <strong>CoroutineScope</strong>. If that scope gets cancelled:</p><ul><li>The collect will throw a <strong>CancellationException</strong> internally.</li><li>Flow builder operators (flow, map, filter, etc.) are built with <strong>suspending functions</strong> → They immediately stop when CancellationException is thrown.</li><li>Any suspending function inside flow builder respects cancellation.</li></ul><h4>1. Flow is Bound to CoroutineScope</h4><ul><li>Every time you call .collect(), it runs inside a <strong>CoroutineScope</strong>.</li><li>When the <strong>scope’s Job is cancelled</strong> (for example, when Activity is destroyed or you cancel manually), the <strong>Flow is automatically cancelled</strong>.</li><li>This behavior is part of <strong>Structured Concurrency</strong> — child coroutines (like Flow) follow the lifecycle of their parent scope.</li></ul><h4>2. CancellationException is Thrown</h4><ul><li>When cancellation happens, Flow <strong>throws a </strong><strong>CancellationException internally</strong>.</li><li>This exception <strong>propagates upwards</strong> and immediately <strong>stops the Flow collection</strong>.</li><li>You can detect this cancellation using .onCompletion {} or .catch {} operators.</li></ul><pre>flow<br>    .onCompletion { cause -&gt;<br>        if (cause is CancellationException) {<br>            println(&quot;Flow Cancelled!&quot;)<br>        }<br>    }<br>    .collect { value -&gt; println(value) }</pre><h4>3. Suspending Functions Auto-Check Cancellation</h4><p>All suspending functions used inside Flow (like emit(), delay(), withContext())<br> <strong>automatically check for cancellation.</strong></p><p>Internally, they check</p><pre>coroutineContext.job.isActive</pre><p>If isActive == false, they throw <strong>CancellationException</strong> → Flow stops.</p><h4>4. Non-Suspending Work Needs Manual Check</h4><p>If you are doing <strong>heavy CPU work</strong> (like for-loop, calculations) inside flow {},<br> <strong>It won’t auto-cancel.</strong><br> You need to manually check for cancellation using</p><pre>coroutineContext.ensureActive()</pre><pre>flow {<br>    for (i in 1..1000) {<br>        ensureActive() // Manual check<br>        emit(i)<br>    }<br>}</pre><h4><strong>How Cancellation Signal Travels</strong></h4><pre>CoroutineScope Cancelled ➜ Job Cancelled ➜ collect() Cancelled ➜ Flow Stops</pre><h4>Imagine a Water Pipeline Example</h4><p>Think of <strong>Flow</strong> like a <strong>water pipeline</strong>.</p><ul><li>The <strong>Pipeline = CoroutineScope</strong></li><li>The <strong>Tap = collect() function</strong></li><li>The <strong>Water = Flow emissions (data items)</strong></li></ul><p>Now, when you <strong>close the main valve (Scope is cancelled):</strong></p><ol><li><strong>Pipeline gets blocked (Job is marked cancelled)</strong></li><li>The <strong>Tap (collect) stops working</strong></li><li><strong>Water flow (emission) stops</strong></li></ol><p>This is exactly how <strong>Flow cancellation works internally.</strong><br> If the <strong>main source is shut off (scope), the whole chain breaks.</strong></p><h4>Key Flow Cancellation Operators &amp; Techniques</h4><h4>1. onCompletion { }</h4><ul><li><strong>Purpose:</strong> Detect when Flow completes <strong>normally or by cancellation.</strong></li><li><strong>Use:</strong> Check if Flow was cancelled.</li></ul><pre>flow<br>    .onCompletion { cause -&gt;<br>        if (cause is CancellationException) {<br>            println(&quot;Flow Cancelled&quot;)<br>        }<br>    }<br>    .collect { println(it) }</pre><h4>2. catch { }</h4><ul><li><strong>Purpose:</strong> Handle <strong>exceptions</strong> including CancellationException.</li><li><strong>Note:</strong> It only catches exceptions <strong>before terminal operators like collect()</strong>.</li></ul><pre>flow<br>    .catch { e -&gt; println(&quot;Flow Failed: $e&quot;) }<br>    .collect { println(it) }</pre><h4>3. cancellable()</h4><ul><li><strong>Purpose:</strong> Makes a Flow <strong>cooperatively cancellable.</strong></li><li>It adds a <strong>cancellation check</strong> between emissions.</li></ul><pre>flow<br>    .cancellable()<br>    .collect { println(it) }</pre><h4>4. Flow Scope Cancellation</h4><ul><li><strong>Directly cancelling the CoroutineScope</strong> in which Flow is collected.</li></ul><pre>val job = CoroutineScope(Dispatchers.Main).launch {<br>    flow.collect { println(it) }<br>}<br>job.cancel() // Cancels flow</pre><h4>5. Manual Cancellation Checks</h4><p>For heavy or CPU-bound operations:</p><ul><li>Use <strong>ensureActive()</strong> or <strong>coroutineContext.isActive</strong></li></ul><pre>flow {<br>    for (i in 1..1000) {<br>        ensureActive()<br>        emit(i)<br>    }<br>}</pre><h4>Timeout Cancellation in Flow</h4><p>Timeout cancellation is when you want to <strong>automatically cancel the Flow</strong> if it <strong>doesn’t complete within a specific time.</strong></p><h4>1. withTimeout { }</h4><ul><li><strong>Cancels the entire coroutine &amp; flow if it doesn’t complete in time.</strong></li><li>Throws <strong>TimeoutCancellationException</strong>.</li></ul><pre>try {<br>    withTimeout(3000) { // 3 sec timeout<br>        flow.collect { println(it) }<br>    }<br>} catch (e: TimeoutCancellationException) {<br>    println(&quot;Flow timed out!&quot;)<br>}</pre><h4>2. withTimeoutOrNull { }</h4><ul><li>Similar to withTimeout but returns <strong>null</strong> instead of throwing an exception.</li></ul><pre>val result = withTimeoutOrNull(3000) {<br>    flow.collect { println(it) }<br>}<br>if (result == null) {<br>    println(&quot;Flow timed out and returned null&quot;)<br>}</pre><h4>How it works internally</h4><ul><li><strong>Timeout uses coroutine cancellation.</strong><br> When time exceeds → <strong>Job is cancelled</strong> → <strong>Flow emits CancellationException</strong> → Flow <strong>stops immediately.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*lCRJyynnlkwrg7uUoPpcPw.png" /></figure><h4>How Structured Concurrency helps with Flow Cancellation</h4><h4>What is Structured Concurrency?</h4><p>It means → <strong>A child coroutine/Flow cannot live longer than its parent scope.</strong><br> <strong>When parent is cancelled, all its children (including Flow) are also cancelled.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*2vA59gjnfL0H62OC8zn5dg.png" /></figure><pre>lifecycleScope.launch {<br> flow.collect { println(it) } // Will auto-cancel when lifecycleScope is destroyed<br>}</pre><p>When <strong>Activity/Fragment is destroyed → lifecycleScope is cancelled → Flow collection stops safely.</strong></p><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16e50f7c3bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin Flow: Collecting and Context]]></title>
            <link>https://medium.com/@guruprasadhegde4/mastering-kotlin-flow-collecting-and-context-e5b379f03cab?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5b379f03cab</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[collecting]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 09:46:35 GMT</pubDate>
            <atom:updated>2025-03-25T09:46:35.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OUogswBNEsYYilFaVu8MQ.png" /></figure><h3>Collecting Flow: collect vs collectLatest:</h3><h4>What is collect?</h4><ul><li><strong>Definition</strong>: The collect function is a terminal operator used to collect all emitted values from a flow sequentially.</li><li><strong>Behavior</strong>: Each emission is processed in the order it is emitted. Subsequent emissions wait for the current one to finish processing.</li><li><strong>Use Case</strong>: Use when every emitted value must be handled without interruption.</li></ul><h4>collect Example: Downloading Files Sequentially</h4><p>You are downloading a list of files, and every file must be downloaded completely. No file can be skipped or interrupted</p><pre>val fileFlow = flowOf(&quot;File1&quot;, &quot;File2&quot;, &quot;File3&quot;)<br><br>fileFlow.collect { file -&gt;<br>    println(&quot;Downloading $file...&quot;)<br>    delay(3000) // Simulate download time<br>    println(&quot;$file downloaded successfully!&quot;)<br>}<br><br>// output <br>Downloading File1...<br>File1 downloaded successfully!<br>Downloading File2...<br>File2 downloaded successfully!<br>Downloading File3...<br>File3 downloaded successfully!</pre><h4>Key Points:</h4><ul><li>Each file is processed completely before moving to the next one.</li><li>This ensures that all files are downloaded sequentially, with no skipping.</li></ul><h4>What is collectLatest?</h4><ul><li><strong>Definition</strong>: The collectLatest function is a terminal operator that cancels the processing of the previous emission if a new one is emitted before it completes.</li><li><strong>Behavior</strong>: Only the most recent emission is processed, making it suitable for handling fast data streams where intermediate values can be discarded.</li><li><strong>Use Case</strong>: Use when you are interested in only the latest data, such as updating a UI or handling real-time events.</li></ul><h4>collectLatest Example: Search Suggestions</h4><p>A user types in a search bar, and you want to fetch suggestions based on the latest input. You don’t want to process outdated queries if the user types quickly.</p><pre>val searchFlow = flow {<br>    emit(&quot;A&quot;) // Simulate the user typing &quot;A&quot;<br>    delay(500) // Simulate delay between typing<br>    emit(&quot;AB&quot;) // The user types &quot;B&quot; after &quot;A&quot;<br>    delay(500)<br>    emit(&quot;ABC&quot;) // The user types &quot;C&quot; after &quot;AB&quot;<br>}<br><br>searchFlow.collectLatest { query -&gt;<br>    println(&quot;Fetching suggestions for: $query&quot;)<br>    delay(1500) // Simulate network call to fetch suggestions<br>    println(&quot;Suggestions for $query fetched&quot;)<br>}<br><br>// Output <br>Fetching suggestions for: ABC<br>Suggestions for ABC fetched<br></pre><h4>Key Differences Between collect and collectLatest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*ychC4UfrnF1mYc1Q02T7fg.png" /></figure><h4>When to Use ?</h4><h4>Use collect When:</h4><ol><li><strong>Every Emission Matters</strong>: All data is important, e.g., logging or aggregating all values.</li><li><strong>Sequential Processing</strong>: Processing order is critical.</li></ol><h4>Use collectLatest When:</h4><ol><li><strong>Only Latest Data is Relevant</strong>: Updating UI or handling fast, frequent events.</li><li><strong>Avoid Long Processing Delays</strong>: Skips redundant tasks for better responsiveness.</li></ol><h4>Key Points to Remember</h4><ol><li><strong>Cancellable Nature</strong>:</li></ol><ul><li>collect waits for the current emission to complete.</li><li>collectLatest cancels previous emissions mid-processing.</li></ul><p><strong>2. Performance Optimization</strong>:</p><ul><li>Use collectLatest for real-time scenarios to avoid lag.</li><li>Prefer collect when all values contribute to the result.</li></ul><p><strong>3. Thread Safety</strong>:</p><ul><li>Both functions respect coroutine context and ensure safe execution.</li></ul><h3>Context Preservation in Kotlin Flow:</h3><h4>What is Context Preservation?</h4><ul><li><strong>Definition</strong>: In Kotlin Flow, <strong><em>the upstream flow (emission and transformation operations)</em></strong> executes in the same coroutine context as the collector by default, ensuring seamless context management and reducing the risk of context mismanagement.</li><li><strong>Implication</strong>: Operations like map, filter, or even the emission itself inherit the context of the collect function unless overridden with flowOn.</li></ul><h4>Why Context Preservation Matters</h4><ul><li><strong>Predictable Behavior</strong>: Ensures that all flow operations run in the same context unless explicitly altered.</li><li><strong>Thread Safety</strong>: Prevents unintentional context switches, which could lead to race conditions.</li><li><strong>Performance Optimization</strong>: By default, flow avoids unnecessary overhead from context switches.</li></ul><h4>Flow’s Default Context Behavior</h4><p>Without any explicit context modification, all flow operations execute on the <strong>collector’s coroutine context</strong>.</p><pre>val myFlow = flow {<br>    println(&quot;Emitting on: ${Thread.currentThread().name}&quot;)<br>    emit(1)<br>}<br><br>runBlocking {<br>    myFlow.collect { value -&gt;<br>        println(&quot;Collected $value on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br><br>// Output <br><br>Emitting on: main<br>Collected 1 on: main</pre><p>Both emission and collection occur on the main thread.</p><h4>Changing Context with &quot;flowOn&quot;</h4><p>To modify the context of upstream operations, use the flowOn operator. This shifts the upstream flow to a different context, independent of the collector.</p><pre>val myFlow = flow {<br>    println(&quot;Emitting on: ${Thread.currentThread().name}&quot;)<br>    emit(1)<br>}.flowOn(Dispatchers.IO)<br><br>runBlocking {<br>    myFlow.collect { value -&gt;<br>        println(&quot;Collected $value on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br><br>// Output <br><br>Emitting on: DefaultDispatcher-worker-1<br>Collected 1 on: main</pre><p>flowOn(Dispatchers.IO) moves the upstream operations to a background thread (DefaultDispatcher-worker-1), while the collection occurs on the main thread.</p><h4>Key Points:</h4><ul><li>flowOn changes the context for all upstream operations <strong>before</strong> it in the flow chain.</li><li>Downstream operations (e.g., collect) continue to run in the collector’s context.</li></ul><h4>Difference b/w “flowOn&quot; vs “withContext&quot;</h4><p>While both flowOn and withContext change coroutine contexts, they serve different purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*DHXDKTWPOBFN0qzV3UtWUQ.png" /></figure><p>Example: withContext</p><pre>val myFlow = flow {<br>    withContext(Dispatchers.IO) {<br>        println(&quot;Emitting on: ${Thread.currentThread().name}&quot;)<br>        emit(1)<br>    }<br>}<br><br>runBlocking {<br>    myFlow.collect { value -&gt;<br>        println(&quot;Collected $value on: ${Thread.currentThread().name}&quot;)<br>    }<br>}<br><br>// Output <br><br>Emitting on: DefaultDispatcher-worker-1<br>Collected 1 on: main</pre><h4>Thread Safety and Best Practices</h4><h4>a. Thread Safety in Flows</h4><p>Flows are inherently thread-safe, but developers must ensure they:</p><ul><li>Use flowOn to shift contexts correctly.</li><li>Avoid shared mutable state within flows unless synchronized.</li></ul><h4>b. Avoid Overusing flowOn</h4><p>Excessive use of flowOn can complicate flow chains and degrade performance.</p><h3>Summary</h3><ol><li><strong>Default Context</strong>: Flow operations execute in the collector’s context unless explicitly changed.</li><li><strong>flowOn</strong>: Use to shift upstream operations to a different context.</li><li><strong>Context Preservation</strong>: Ensures predictable and efficient flow execution.</li></ol><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5b379f03cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of Kotlin Flow]]></title>
            <link>https://medium.com/@guruprasadhegde4/basics-of-kotlin-flow-d782a65c2300?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d782a65c2300</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 06:05:51 GMT</pubDate>
            <atom:updated>2025-01-15T06:05:51.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*8qaqTHsHpTToyN8FMQMgEw.jpeg" /></figure><h3>What is Flow?</h3><p><strong>Flow</strong> is a <strong>reactive streams API</strong> in Kotlin, part of Kotlin Coroutines, “<strong><em>designed to handle asynchronous data streams”</em></strong><em>. </em><strong><em>It allows values to be emitted sequentially and collected asynchronously</em></strong><em>,</em> making it ideal for managing real-time or continuous data updates, such as UI updates, network responses, or database changes.</p><p><strong>“Designed to handle asynchronous data streams” means that Flow is built to manage data that is:</strong></p><ul><li><strong>Generated over time</strong>: Data doesn’t arrive all at once; it comes piece by piece (e.g., messages, live updates, or sensor data).</li><li><strong>Handled without blocking</strong>: Flow lets you process this data in the background (asynchronously) without stopping other parts of your app.</li></ul><h4>Simple Example of Asynchronous Data Streams:</h4><p>Imagine you’re <strong>waiting for a bus</strong> at a bus stop:</p><ul><li>Buses don’t come all at once; they arrive one by one over time.</li><li>You wait at the bus stop, but while waiting, you can check your phone, talk to someone, or do other things (you’re not blocked).</li><li>Each time a bus arrives, you decide whether to get on or wait for the next one.</li></ul><p><strong>Flow</strong> works similarly:</p><ul><li>It handles data (like the buses) that comes piece by piece over time.</li><li>It lets you keep working (doing other tasks in your app) while waiting for each new piece of data to arrive.</li><li>When data (a bus) arrives, it reacts and processes it.</li></ul><p>This makes Flow perfect for real-time updates like notifications, live messages, or user actions.</p><p><strong>“It allows values to be emitted sequentially and collected asynchronously” means:</strong></p><ol><li><strong>Emitted Sequentially</strong>:</li></ol><ul><li>Data (values) is sent out (emitted) one after another in a specific order.</li><li>Example: Imagine a vending machine giving out snacks one by one, in the order you selected.</li></ul><p><strong>2. Collected Asynchronously</strong>:</p><ul><li>The person receiving (collecting) the snacks can take them without stopping the vending machine from working.</li><li>In code, this means your app can process each piece of data as it arrives without blocking other tasks.</li></ul><h4>Real-World Example:</h4><p>Think of watching a live cricket score:</p><ul><li>The scores are updated one at a time (emitted sequentially).</li><li>You receive (collect) the scores in real-time on your phone while still using the phone for other things (asynchronously).</li></ul><h3>Why do we need Flow ?</h3><h4>1. Handle Real-Time Data</h4><ul><li>Manage streams like live updates, user interactions, or database changes seamlessly.</li></ul><h4>2. Work Asynchronously</h4><ul><li>Process data without blocking the app, keeping it responsive.</li></ul><h4>3. Simplify Reactive Programming</h4><ul><li>Write clean, structured code for managing continuous data efficiently.</li></ul><p>Flow makes handling <strong>asynchronous streams</strong> easy and avoids common issues like thread blocking or callback hell.</p><h3>Difference Between Flow and LiveData</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*HpdejPH81GdL8F6i2t70Eg.png" /></figure><p><strong>Why do we prefer Flow over LiveData, even though LiveData is lifecycle-aware and stops updates when not active, while Flow requires manual lifecycle handling?</strong></p><p>While <strong>LiveData</strong> is lifecycle-aware, <strong>Flow</strong> is preferred in many cases because it offers several advantages:</p><ol><li><strong>More Flexibility</strong>:</li></ol><ul><li><strong>Flow</strong> supports complex operations, such as combining, transforming, and flattening data streams using operators like map, filter, flatMap, and more.</li><li><strong>LiveData</strong> is simpler and mostly limited to observing and updating data on the UI thread.</li></ul><p><strong>2. Integration with Kotlin Coroutines</strong>:</p><ul><li><strong>Flow</strong> is fully integrated with Kotlin Coroutines, making it easier to handle background tasks asynchronously (e.g., network calls, DB operations) without blocking the main thread.</li><li><strong>LiveData</strong> was designed before Kotlin Coroutines and isn’t as naturally suited for complex asynchronous tasks.</li></ul><p><strong>3. Handling Asynchronous Data</strong>:</p><ul><li><strong>Flow</strong> handles asynchronous streams and can emit multiple values over time. It can be used in more advanced scenarios like network updates, data processing, and continuous real-time data.</li><li><strong>LiveData</strong> is designed for more straightforward use cases, like single data updates tied to lifecycle events (UI).</li></ul><p><strong>4. Manual Lifecycle Control</strong>:</p><ul><li>Even though <strong>Flow</strong> is not lifecycle-aware by default, it provides greater control over how and when you collect the data (using launchIn, collect, etc.). You can handle lifecycle events more explicitly.</li><li><strong>LiveData</strong> abstracts this away for simplicity but offers less control when complex scenarios arise.</li></ul><h4>When to Choose Flow:</h4><ul><li>If you need more advanced operations, complex data transformations, or asynchronous operations.</li><li>If you want to integrate with Kotlin Coroutines and handle multiple data updates over time.</li></ul><h4>When to Choose LiveData:</h4><ul><li>If you have a simpler UI-driven app where you just need to observe changes to data and don’t require advanced flow operations or background tasks.</li></ul><h3>Cold vs Hot Flows: Understand how Flow is cold.</h3><h4>Cold Flow:</h4><p>A <strong>cold flow</strong> in Kotlin is a flow that <strong>does not produce any data until it’s collected</strong>. The flow is created and its values are emitted <strong>only when</strong> a <strong>collector</strong> starts collecting it. If no one is collecting it, the flow doesn’t perform any work or emit any values.</p><p>Key Points about <strong>Cold Flow or Why Flow is Cold</strong>:</p><ol><li><strong>Lazy Execution</strong>: Cold flows are lazy, meaning the data is <strong>not generated</strong> until a collector subscribes to it. The flow doesn’t start emitting items on its own.</li><li><strong>Re-Execution</strong>: Every time a new collector starts collecting, the flow <strong>restarts from the beginning</strong>. If you collect a cold flow multiple times, it will re-execute its block each time, emitting the data from the start.</li><li><strong>Memory Efficiency</strong>: Since the flow is cold, it only emits data when needed. This can be more memory-efficient as it doesn’t continuously emit or hold data.</li><li><strong>Independent for Each Collector</strong>: Each collector gets its own sequence of emissions. This is particularly useful when you want independent data streams for each observer.</li></ol><pre>fun fetchData(): Flow&lt;Int&gt; = flow {<br>    println(&quot;Fetching data...&quot;)<br>    for (i in 1..3) {<br>        delay(1000) // Simulating a network or database call<br>        emit(i) // Emitting data<br>    }<br>}<br><br>suspend fun main() {<br>    fetchData().collect { value -&gt; println(&quot;Collected: $value&quot;) }<br>    fetchData().collect { value -&gt; println(&quot;Collected again: $value&quot;) }<br>}<br><br><br>// Output <br>Fetching data...<br>Collected: 1<br>Fetching data...<br>Collected again: 1</pre><p>The flow is executed from the beginning each time it is collected.</p><h4>How Cold Flow Works:</h4><ul><li>When you call fetchData(), it <strong>doesn’t emit any values</strong> yet. It’s just a definition of how values will be emitted.</li><li>Only when you <strong>call </strong><strong>collect</strong> is when the flow <strong>starts executing</strong> and emits values.</li><li>The next time you collect it, the flow <strong>restarts</strong> and re-executes, even if the previous collector received values already.</li></ul><blockquote><strong>Why is Flow Cold</strong></blockquote><blockquote><strong>Flow is cold because it only starts sending data when someone collects it. Until then, it does nothing. Every time you collect it, it starts from the beginning and sends fresh data. This way, it only does work when needed, saving resources.</strong></blockquote><h3>Hot Flow (Contrast with Cold Flow):</h3><p>In contrast, <strong>hot flows</strong> start emitting data as soon as they are created, and the data is <strong>shared across all collectors</strong>. Hot flows do not wait for a collector to begin emitting data; they are active once created, and any collector can join at any time and get the data emitted so far.</p><ul><li><strong>Example</strong>: StateFlow and SharedFlow are examples of hot flows, where the data is continuously emitted even if no collector is listening, and all collectors share the same emitted data.</li></ul><h3>When to Use Cold Flows:</h3><ul><li><strong>When you want to control the start of data emission</strong>. Cold flows allow you to lazily execute code only when you need it.</li><li><strong>Independent Data Streams</strong>: If each collector should have its own independent stream of data (e.g., separate API calls for each user), cold flows are a good fit.</li><li><strong>Memory Efficiency</strong>: Since cold flows don’t start until collected, they help reduce unnecessary computations and memory usage.</li></ul><h3>Summary:</h3><ul><li><strong>Cold Flow</strong>: Doesn’t emit until collected, starts fresh for each collector, and executes lazily.</li><li><strong>Hot Flow</strong>: Emits immediately and shares data across all collectors without waiting.</li></ul><h3>What Are Flow Builders?</h3><p><strong>Flow builders</strong> in Kotlin are functions that help you create <strong>Flow</strong> instances to emit values in a specific manner. They act as tools to generate flows that produce data streams.</p><h3>Why Are Flow Builders Important?</h3><ul><li>They provide an easy and structured way to create flows.</li><li>They let you define how data is emitted, making it suitable for asynchronous or real-time data streams.</li><li>They simplify working with dynamic data sources like APIs, databases, or UI events.</li></ul><p>In short, flow builders help define <strong>how data flows</strong> in a coroutine-based environment.</p><h3>Types of Flow Builders</h3><p><strong>1. flow {}(Custom Flow)</strong></p><ul><li>The most commonly used builder.</li><li>Creates a cold flow that emits values sequentially.</li><li>Suitable for emitting values manually or performing operations like database queries or network calls.</li></ul><pre>fun fetchNumbers(): Flow&lt;Int&gt; = flow {<br>    for (i in 1..5) {<br>        delay(500) // Simulate a delay<br>        emit(i) // Emit each number<br>    }<br>}<br><br>suspend fun main() {<br>    fetchNumbers().collect { println(&quot;Received: $it&quot;) }<br>}<br><br>// output <br><br>Received: 1<br>Received: 2<br>Received: 3<br>Received: 4<br>Received: 5</pre><p><strong>2. flowOf(vararg value) (Static Flow)</strong></p><ul><li>Emits a fixed set of values.</li><li>Best for simple flows with predefined data.</li></ul><pre>val fruits = flowOf(&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;)<br><br>suspend fun main() {<br>    fruits.collect { println(&quot;Fruit: $it&quot;) }<br>}<br><br>// output <br><br>Fruit: Apple<br>Fruit: Banana<br>Fruit: Cherry</pre><p><strong>3. asFlow() (Convert Collection to Flow)</strong></p><ul><li>Converts a collection, sequence, or array into a flow.</li><li>Great for transforming existing data into a flow</li></ul><pre>val numbers = listOf(10, 20, 30).asFlow()<br><br>suspend fun main() {<br>    numbers.collect { println(&quot;Number: $it&quot;) }<br>}<br><br>// output<br><br>Number: 10<br>Number: 20<br>Number: 30</pre><p><strong>4. channelFlow {} (Concurrent Flow)</strong></p><ul><li>A more advanced builder for creating <strong>hot flows</strong>.</li><li>Allows for concurrent emissions and is used when working with multiple coroutines.</li></ul><pre>fun fetchDataConcurrently(): Flow&lt;Int&gt; = channelFlow {<br>    launch { send(1) }<br>    launch { send(2) }<br>    launch { send(3) }<br>}<br><br>suspend fun main() {<br>    fetchDataConcurrently().collect { println(it) }<br>}<br><br>// output <br><br>1<br>2<br>3</pre><p><strong>5. emptyFlow {} (No Data Flow)</strong></p><ul><li>Creates a flow that emits no values.</li><li>Useful for returning “no data” states.</li></ul><pre>val noData = emptyFlow&lt;String&gt;()<br><br>suspend fun main() {<br>    noData.collect { println(&quot;This won&#39;t be printed!&quot;) }<br>}<br><br></pre><p><strong>6. flowOn {}(Not a Builder, but Important)</strong></p><ul><li>Specifies the coroutine context (dispatcher) where the flow will emit values.</li><li>Helps separate emission context from collection context.</li></ul><pre>val flowWithDispatcher = flow {<br>    emit(&quot;Working on background thread&quot;)<br>}.flowOn(Dispatchers.IO)<br><br>suspend fun main() {<br>    flowWithDispatcher.collect { println(it) }<br>}</pre><h3>Key Points to Remember</h3><ol><li><strong>Cold by Default</strong>: All flows created by these builders are cold, meaning they start emitting data only when collected.</li><li><strong>Sequential Emission</strong>: Builders like flow {} and flowOf() emit values one after another.</li><li><strong>Flexibility</strong>: Builders allow you to create flows for any use case, from simple static data to complex concurrent operations.</li><li><strong>Error Handling</strong>: All builders support try-catch blocks to handle errors gracefully within the flow.</li></ol><h3>When to Use Each Builder?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jprlefyt-RZw4dsT4BIpxw.png" /></figure><h3>What are Kotlin Flow Operators?</h3><p>Kotlin Flow operators are functions that help process, transform, and control data streams emitted by a <strong>Flow</strong>. These operators make it easier to work with asynchronous data by providing tools for <strong>filtering</strong>, <strong>mapping</strong>, <strong>combining</strong>, and <strong>handling errors</strong> in a clean and readable way.</p><h3>1. Transform Operators</h3><h4>Example 1: map</h4><p>Transform each emitted value.<br><strong>Use Case</strong>: Convert Celsius temperatures to Fahrenheit.</p><pre>flowOf(0, 20, 30).map { it * 9 / 5 + 32 }<br>    .collect { println(&quot;Fahrenheit: $it&quot;) }<br>// Output: Fahrenheit: 32, Fahrenheit: 68, Fahrenheit: 86</pre><h4>Example 2: flatMapConcat</h4><p>Transform each value into another flow and concatenate them sequentially.<br><strong>Use Case</strong>: Generate a sequence for each value.</p><pre>flowOf(1, 2).flatMapConcat { flowOf(&quot;$it-A&quot;, &quot;$it-B&quot;) }<br>    .collect { println(it) }<br>// Output: 1-A, 1-B, 2-A, 2-B</pre><h4>Example 3: transform</h4><p>Emit multiple values or perform actions during transformation.<br><strong>Use Case</strong>: Emit a value and its square.</p><pre>flowOf(2, 3).transform {<br>    emit(&quot;Original: $it&quot;)<br>    emit(&quot;Square: ${it * it}&quot;)<br>}.collect { println(it) }<br>// Output: Original: 2, Square: 4, Original: 3, Square: 9</pre><h3>2. Filtering Operators</h3><h4>Example 4: filter</h4><p>Emit only values that meet a condition.<br><strong>Use Case</strong>: Emit only even numbers.</p><pre>flowOf(1, 2, 3, 4).filter { it % 2 == 0 }<br>    .collect { println(&quot;Even: $it&quot;) }<br>// Output: Even: 2, Even: 4</pre><h4>Example 5: take</h4><p>Emit only the first N values.<br><strong>Use Case</strong>: Limit data for initial processing.</p><pre>flowOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;).take(2)<br>    .collect { println(it) }<br>// Output: A, B</pre><h4>Example 6: distinctUntilChanged</h4><p>Skip consecutive duplicate values.<br><strong>Use Case</strong>: Filter repeated user inputs.</p><pre>flowOf(1, 1, 2, 2, 3).distinctUntilChanged()<br>    .collect { println(it) }<br>// Output: 1, 2, 3</pre><h3>3. Combining Operators</h3><h4>Example 7: zip</h4><p>Combine values from two flows into pairs.<br><strong>Use Case</strong>: Pair a list of IDs with names.</p><pre>val ids = flowOf(101, 102)<br>val names = flowOf(&quot;Alice&quot;, &quot;Bob&quot;)<br>ids.zip(names) { id, name -&gt; &quot;$id: $name&quot; }<br>    .collect { println(it) }<br>// Output: 101: Alice, 102: Bob</pre><h4>Example 8: combine</h4><p>Combine the latest values from two flows.<br><strong>Use Case</strong>: Show real-time data updates.</p><pre>val temperature = flowOf(20, 22, 24).onEach { delay(200) }<br>val humidity = flowOf(60, 65).onEach { delay(300) }<br>temperature.combine(humidity) { temp, hum -&gt; &quot;Temp: $temp, Humidity: $hum&quot; }<br>    .collect { println(it) }<br>// Output: Temp: 20, Humidity: 60, Temp: 22, Humidity: 60, Temp: 24, Humidity: 65</pre><h3>4. Terminal Operators</h3><h4>Example 9: collect</h4><p>Collect and print all emitted values.<br><strong>Use Case</strong>: Process API results.</p><pre>flowOf(&quot;Item1&quot;, &quot;Item2&quot;, &quot;Item3&quot;).collect { println(&quot;Received: $it&quot;) }<br>// Output: Received: Item1, Received: Item2, Received: Item3</pre><h4>Example 10: toList</h4><p>Convert a flow to a list.<br><strong>Use Case</strong>: Gather results for batch processing.</p><pre>flow {<br>    emit(1)<br>    emit(2 / 0) // Causes an exception<br>}.catch { emit(-1) }<br>    .collect { println(it) }<br>// Output: 1, -1</pre><h4>Example 12: retry</h4><p>Retry a flow when it fails.<br><strong>Use Case</strong>: Retry network requests.</p><pre>flow {<br>    emit(1)<br>    throw Exception(&quot;Network Error&quot;)<br>}.retry(2) {<br>    println(&quot;Retrying...&quot;)<br>    true<br>}.catch { println(&quot;Failed: ${it.message}&quot;) }<br>    .collect { println(it) }<br>// Output: Retrying..., Retrying..., Failed: Network Error</pre><h3>Key Takeaways</h3><ul><li><strong>Transform operators</strong> like map and transform modify data.</li><li><strong>Filtering operators</strong> like filter and distinctUntilChanged refine data streams.</li><li><strong>Combining operators</strong> like zip and combine merge multiple flows.</li><li><strong>Error-handling operators</strong> like catch and retry ensure resilience.</li></ul><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d782a65c2300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutine: Advanced Coroutine Cancellation and Timeout Handling]]></title>
            <link>https://medium.com/@guruprasadhegde4/coroutine-advanced-coroutine-cancellation-and-timeout-handling-7ca21c56ff92?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ca21c56ff92</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine-cancellation]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[time-out]]></category>
            <category><![CDATA[koltin]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 13:46:19 GMT</pubDate>
            <atom:updated>2024-11-27T13:46:19.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETMbtxAUaGRpU3UgZwAHtw.png" /></figure><blockquote>Before we dive into advanced coroutine cancellation, <strong>we must first understand how a </strong><strong>Job works and how it moves between states.</strong> Once we have a solid understanding of these concepts, it will be easier to grasp advanced coroutine cancellation.</blockquote><p>In Kotlin Coroutines, a <strong>Job</strong> is a cancellable, lifecycle-aware handle that represents a unit of work being executed within a coroutine.</p><h4>1. Job States in Kotlin Coroutines</h4><p>A Job in Kotlin coroutines represents a unit of work that is executed asynchronously. The Job can be in one of the following states:</p><ul><li><strong>New</strong>: The job has been created, but it has not yet started execution.</li><li><strong>Active</strong>: The job is currently running and performing its tasks.</li><li><strong>Cancelling</strong>: The job is in the process of being canceled, but it hasn’t fully completed the cancellation yet.</li><li><strong>Completed</strong>: The job has finished execution, either successfully or due to cancellation or failure.</li></ul><h4>2. Lifecycle of a Job</h4><p>The lifecycle of a Job can be visualized as follows:</p><ol><li><strong>New</strong>: A job is created but not yet started.</li></ol><ul><li>This happens when you launch a coroutine or create a job explicitly with Job().</li></ul><p><strong>2. Active</strong>: Once the job is started (e.g., a coroutine begins execution), it becomes active.</p><ul><li>The job remains in the “active” state while performing its task, such as computation or I/O operation.</li></ul><p><strong>3. Cancelling</strong>: If a job is canceled either explicitly by calling cancel() or due to the parent coroutine being canceled, it enters the &quot;cancelling&quot; state.</p><ul><li>The cancellation process is cooperative, meaning the job’s coroutine should check for cancellation regularly (e.g., with isActive or ensureActive()).</li></ul><p><strong>4. Completed</strong>: The job is either completed successfully or with failure (due to an exception).</p><ul><li>A job enters this state once the coroutine’s work has finished or the job has been canceled and all cancellation tasks are completed.</li></ul><h4>3. How a Job Moves Between States</h4><ol><li><strong>From New → Active</strong>:</li></ol><ul><li>This transition occurs when the job starts its execution. For a coroutine, this happens when launch() or async() is called and the coroutine&#39;s block of code begins executing.</li></ul><p><strong>2. From Active → Cancelling</strong>:</p><ul><li>A job can transition to the “cancelling” state when cancel() is invoked or if the parent coroutine is canceled. It is important to note that cancellation is a cooperative process, meaning the job must allow cancellation to take place by periodically checking if it is still active (using isActive, for example).</li></ul><p><strong>3. Cancelling → Completed</strong>:</p><ul><li>The “cancelling” state signifies that the job is in the process of being terminated. This happens after a job is canceled, and any resources are cleaned up. Once all tasks are completed (including cancellation logic), the job moves to the “completed” state.</li><li>A job can be successfully completed if it finishes its work without interruption. If the job fails due to an exception, it is still considered “completed,” but in a failed state.</li></ul><p><strong>4. Handling Failure</strong>:</p><ul><li>A job can fail if an exception occurs during its execution. Once the exception is thrown, the job transitions to the “completed” state but marks the completion as “failed.”</li><li>You can observe job completion (success or failure) by registering for the invokeOnCompletion callback, which lets you handle both success and failure scenarios.</li></ul><pre>val job = GlobalScope.launch {<br>    // some task<br>}<br><br>job.invokeOnCompletion { exception -&gt;<br>    if (exception == null) {<br>        println(&quot;Job completed successfully&quot;)<br>    } else {<br>        println(&quot;Job failed with exception: ${exception.message}&quot;)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*0wktHRDU7fBAYIwEE44boQ.png" /></figure><h4>Cancellation Mechanisms in Kotlin Coroutines:</h4><blockquote>Once you understand how a Job moves through its lifecycle, it&#39;s easier to grasp the mechanisms of coroutine cancellation. In Kotlin, cancellation is a crucial concept, especially when working with long-running or asynchronous tasks. Here’s a detailed explanation of how cancellation works in coroutines, how it transitions jobs to the <strong>Cancelling</strong> state, and the various functions involved.</blockquote><h4>1. Understanding Coroutine Cancellation</h4><p>Cancellation in Kotlin coroutines can occur at any point in a coroutine’s lifecycle:</p><ul><li><strong>While Active</strong>: If the job is active and performing its work, it can be canceled. The job will start the cancellation process, but the work will not stop immediately unless the coroutine checks for cancellation.</li><li><strong>During Work Execution</strong>: A coroutine may be executing a task (e.g., a network request, computation) when it is canceled. To handle this, coroutines are designed to check for cancellation regularly (via isActive or ensureActive()).</li><li><strong>Due to an Exception</strong>: If an exception occurs, the coroutine may be canceled and transition to the “completed” state with failure. An exception can also trigger a cancellation, especially if a parent coroutine is canceled.</li></ul><h4>2. Cancellation Functions</h4><p>Several key functions in Kotlin coroutines help you manage the cancellation process:</p><h4>cancel()</h4><p>The cancel() function is used to cancel a job explicitly. Once called, the job transitions from <strong>Active</strong> to <strong>Cancelling</strong>.</p><p><strong>Behavior</strong>: It initiates the cancellation process but doesn’t immediately stop the work. The job will continue running until it reaches a cancellation checkpoint (e.g., by checking isActive).</p><p><strong>Example:</strong></p><pre>val job = GlobalScope.launch {<br>    repeat(1000) { i -&gt;<br>        if (!isActive) return@launch  // Cancellation checkpoint<br>        println(i)<br>        delay(100L)<br>    }<br>}<br><br>job.cancel()  // This cancels the job</pre><p>In this example, the job checks for cancellation at each step, and once cancel() is called, the job transitions to <strong>Cancelling</strong> and eventually completes.</p><h4>cancelAndJoin()</h4><p>The cancelAndJoin() function cancels the job and then waits for its completion, which is useful when you need to wait for the cancellation process to finish.</p><ul><li><strong>Behavior</strong>: It cancels the job and suspends the calling thread until the job completes its cancellation.</li><li><strong>Example</strong>:</li></ul><pre>val job = GlobalScope.launch {<br>    delay(1000L)<br>    println(&quot;Job completed&quot;)<br>}<br><br>job.cancelAndJoin()  // Cancels the job and waits for completion<br>println(&quot;Job is cancelled&quot;)</pre><p>Here, cancelAndJoin() cancels the job and waits until the cancellation process is fully completed before proceeding.</p><h4>join()</h4><p>The join() function is often used to wait for a job to finish without canceling it. However, if the job is canceled during execution, join() will return after the cancellation process.</p><ul><li><strong>Behavior</strong>: It doesn’t cancel the job but suspends the calling thread until the job finishes.</li><li><strong>Example</strong>:</li></ul><pre>val job = GlobalScope.launch {<br>    delay(1000L)<br>    println(&quot;Job completed&quot;)<br>}<br><br>job.cancel()  // Job is cancelled<br>job.join()    // Waits until job finishes (canceled or completed)</pre><p>After job.cancel() is called, join() ensures the calling thread waits for the job to finish.</p><h4>cancelChildren()</h4><p>This function cancels all child jobs of a parent job. It’s useful when you have nested coroutines and want to cancel everything under a specific scope.</p><ul><li><strong>Behavior</strong>: It cancels all child jobs but doesn’t cancel the parent job itself.</li><li><strong>Example</strong>:</li></ul><pre>val parentJob = Job()<br>val childJob1 = GlobalScope.launch(parentJob) { delay(1000L) }<br>val childJob2 = GlobalScope.launch(parentJob) { delay(1000L) }<br><br>parentJob.cancelChildren()  // Cancels both child jobs but not the parent job</pre><h4><strong>Advanced Coroutine Cancellation :</strong></h4><blockquote>Advanced cancellation in Kotlin coroutines requires an understanding of <strong>structured concurrency</strong>, handling <strong>timeouts</strong>, <strong>cooperative cancellation</strong>, and performing <strong>resource cleanup</strong>. These concepts work together to ensure coroutines can be efficiently canceled at the right points in their lifecycle, particularly by leveraging the <strong>Job states</strong></blockquote><h4>1. Structured Concurrency</h4><p><strong>Structured concurrency</strong> ensures that coroutines are launched within a defined scope (e.g., CoroutineScope), making it easier to manage their lifecycle and cancellation. It prevents coroutines from running beyond the lifecycle of their scope, thus reducing potential issues with orphaned or dangling coroutines.</p><ul><li><strong>Key idea</strong>: Parent jobs automatically cancel their child jobs when they are canceled or completed.</li><li><strong>Example</strong>:</li></ul><pre>val parentJob = CoroutineScope(Dispatchers.Main).launch {<br>    val childJob = launch { <br>        delay(1000L)<br>        println(&quot;Child job completed&quot;)<br>    }<br>}<br><br>parentJob.cancel()  // This will cancel the child job as well</pre><p><strong>Job States in Structured Concurrency</strong>:</p><ul><li><strong>New → Active</strong>: The parent and child jobs are in the Active state while running.</li><li><strong>Cancelling</strong>: Once the parent job is canceled, the child jobs transition to <strong>Cancelling</strong>.</li><li><strong>Completed</strong>: After cleanup, both jobs complete and are in the <strong>Completed</strong> state.</li></ul><p>Structured concurrency simplifies cancellation management by keeping coroutines within a defined scope, making sure cancellations propagate to all jobs within the scope.</p><p><strong>For more information visit : https://medium.com/@guruprasadhegde4/coroutine-structured-concurrency-scope-management-a21962acb2ba</strong></p><h4>2. Handling Timeouts</h4><p>When dealing with potentially long-running tasks, you often need to set time limits, ensuring a job doesn’t run forever. Kotlin coroutines provide built-in mechanisms for timeouts, such as withTimeout() and withTimeoutOrNull().</p><p><strong>withTimeout()</strong>: It throws a TimeoutCancellationException if the coroutine doesn’t complete within the specified time.</p><ul><li><strong>Example</strong>: Imagine you’re building an Android app that fetches user data from a remote server. However, sometimes the network may be slow or unresponsive, and you don’t want to hang the UI for too long. You decide to add a timeout to ensure that if the network request takes longer than a certain amount of time, it will be canceled automatically.</li></ul><pre>import kotlinx.coroutines.*<br>import java.net.SocketTimeoutException<br><br>fun fetchUserData() {<br>    // Launching a coroutine in the IO dispatcher for network calls<br>    GlobalScope.launch(Dispatchers.IO) {<br>        try {<br>            // Setting a timeout of 3 seconds for the network request<br>            withTimeout(3000L) {<br>                // Simulating a network request delay (you would replace this with actual network code)<br>                val userData = fetchFromNetwork()<br>                println(&quot;User data fetched: $userData&quot;)<br>            }<br>        } catch (e: TimeoutCancellationException) {<br>            println(&quot;Request timed out: ${e.message}&quot;)<br>            // Handle the timeout error (e.g., show a message to the user)<br>        }<br>    }<br>}<br><br>suspend fun fetchFromNetwork(): String {<br>    delay(5000L) // Simulate a long-running network operation (5 seconds)<br>    return &quot;User data&quot;<br>}</pre><ul><li>withTimeout(3000L): This sets a timeout of 3 seconds for the fetchFromNetwork() operation.</li><li>If the network request takes longer than 3 seconds, a TimeoutCancellationException is thrown, and the job is canceled.</li><li>Inside the catch block, you can handle the timeout and notify the user that the request took too long.</li></ul><p><strong>Job States During Timeout</strong>:</p><ul><li><strong>Active → Cancelling</strong>: If the timeout occurs, the job is moved to <strong>Cancelling</strong> and then <strong>Completed</strong> with failure (due to timeout).</li></ul><p><strong>withTimeoutOrNull()</strong>: Returns null instead of throwing an exception if the timeout is reached.</p><pre>import kotlinx.coroutines.*<br><br>fun fetchUserData() {<br>    // Launching a coroutine in the IO dispatcher for network calls<br>    GlobalScope.launch(Dispatchers.IO) {<br>        // Using withTimeoutOrNull to return null on timeout<br>        val userData = withTimeoutOrNull(3000L) {<br>            // Simulating a network request delay<br>            fetchFromNetwork()<br>        }<br><br>        if (userData == null) {<br>            println(&quot;Request timed out or was unsuccessful&quot;)<br>            // Handle the timeout error (e.g., retry or show a message)<br>        } else {<br>            println(&quot;User data fetched: $userData&quot;)<br>        }<br>    }<br>}<br><br>suspend fun fetchFromNetwork(): String {<br>    delay(5000L) // Simulate a long-running network operation (5 seconds)<br>    return &quot;User data&quot;<br>}</pre><ul><li>withTimeoutOrNull(3000L): If the fetchFromNetwork() call exceeds 3 seconds, it will return null instead of throwing an exception.</li><li>This allows you to handle timeouts more smoothly without relying on exception handling.</li></ul><p>This allows for clean cancellation when working with time-bound operations.</p><h4>3. Cooperative Cancellation</h4><p><strong>Cooperative cancellation</strong> in Kotlin means that the coroutine itself must be aware of cancellation requests and act accordingly. This is done by regularly checking the job’s cancellation status, typically through the isActive property or ensureActive() function.</p><ul><li><strong>Key concept</strong>: The coroutine must be designed to check for cancellation at appropriate points during execution (e.g., in loops or after heavy computations).</li><li>Example:</li></ul><pre>-val job = GlobalScope.launch {<br>    repeat(1000) { i -&gt;<br>        if (!isActive) return@launch  // Check for cancellation<br>        println(i)<br>        delay(100L)<br>    }<br>}<br><br>job.cancel()  // This triggers cancellation during the next loop iteration</pre><p><strong>Job States During Cooperative Cancellation</strong>:</p><ul><li><strong>Active → Cancelling</strong>: Once cancel() is called, the job moves to <strong>Cancelling</strong>.</li><li><strong>Cancelling → Completed</strong>: After cancellation, the job moves to <strong>Completed</strong>, and any remaining tasks (like resource cleanup) are handled.</li></ul><p><strong>Cooperative cancellation</strong> ensures that the cancellation happens at the earliest possible point in the coroutine, avoiding wasted computation.</p><h4>4. Resource Cleanup</h4><p>When a coroutine is canceled, you often need to clean up resources (e.g., closing files or releasing locks). This is crucial to avoid memory leaks or inconsistent states.</p><ul><li><strong>finally block</strong>: The finally block in a coroutine ensures that resources are cleaned up, even if the job is canceled.</li><li><strong>Example</strong>:</li></ul><pre>val job = GlobalScope.launch {<br>    try {<br>        delay(1000L)  // Simulate long-running task<br>        println(&quot;Task completed&quot;)<br>    } finally {<br>        // Cleanup resources<br>        println(&quot;Cleanup resources&quot;)<br>    }<br>}<br><br>job.cancel()  // Triggers the cleanup</pre><p><strong>Job States and Resource Cleanup</strong>:</p><ul><li><strong>Active → Cancelling</strong>: As soon as cancellation occurs, the finally block is executed for cleanup.</li><li><strong>Cancelling → Completed</strong>: The job transitions to <strong>Completed</strong> once cleanup is finished, either successfully or with failure.</li></ul><h4>Summary of Advanced Cancellation Concepts</h4><ul><li><strong>Structured Concurrency</strong>: Ensures coroutines are scoped and automatically canceled when the scope is canceled.</li><li><strong>Handling Timeouts</strong>: Functions like withTimeout() and withTimeoutOrNull() help manage time-bound operations, transitioning jobs to <strong>Cancelling</strong> if they exceed the time limit.</li><li><strong>Cooperative Cancellation</strong>: Coroutines must check for cancellation regularly using isActive or ensureActive() to cancel efficiently.</li><li><strong>Resource Cleanup</strong>: Use the finally block to clean up resources when a job is canceled, ensuring proper resource management.</li></ul><h4>Key Takeaways</h4><ul><li><strong>Job States (Active → Cancelling → Completed)</strong> are central to understanding how cancellation works.</li><li><strong>Timeouts</strong> and <strong>cooperative cancellation</strong> allow you to handle long-running operations safely and efficiently.</li><li><strong>Structured concurrency</strong> provides automatic cancellation propagation within scopes, making complex coroutine management simpler.</li><li><strong>Resource cleanup</strong> in cancellation ensures that resources are properly released when a coroutine is canceled.</li></ul><h4>Timeout Handling :</h4><h4>What is Timeout handling ?</h4><p><strong>Timeout handling in Kotlin Coroutines</strong> is the process of limiting the execution time of a coroutine using mechanisms like withTimeout or withTimeoutOrNull, ensuring the coroutine is cancelled if it exceeds a specified duration.</p><h4>1. withTimeout:</h4><ul><li><strong>Definition</strong>: Executes a block of code and cancels the coroutine if it doesn’t complete within the specified timeout.</li><li><strong>Throws Exception</strong>: On timeout, it throws a TimeoutCancellationException.</li><li><strong>Use Case</strong>: Use when you need to enforce a strict timeout and handle exceptions.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    try {<br>        withTimeout(1000L) { // Timeout of 1 second<br>            repeat(5) { i -&gt;<br>                println(&quot;Processing $i&quot;)<br>                delay(500L)<br>            }<br>        }<br>    } catch (e: TimeoutCancellationException) {<br>        println(&quot;Operation timed out!&quot;)<br>    }<br>}</pre><pre>Processing 0<br>Processing 1<br>Operation timed out!</pre><h4>2. withTimeoutOrNull:</h4><ul><li><strong>Definition</strong>: Similar to withTimeout, but instead of throwing an exception, it returns null when the timeout is reached.</li><li><strong>No Exception</strong>: Cleaner handling without the need for try-catch.</li><li><strong>Use Case</strong>: Use when a timeout is expected and you prefer returning a fallback value.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val result = withTimeoutOrNull(1000L) { // Timeout of 1 second<br>        repeat(5) { i -&gt;<br>            println(&quot;Processing $i&quot;)<br>            delay(500L)<br>        }<br>        &quot;Success&quot; // Result if completed<br>    }<br><br>    println(result ?: &quot;Operation timed out!&quot;) // Handle null<br>}</pre><pre>Processing 0<br>Processing 1<br>Operation timed out!</pre><h4>3. Differences:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*JY8O_KpaJwMcPRF5Rkwc2g.png" /></figure><p><strong>withTimeout</strong>:</p><ul><li>Critical operations where a timeout must be enforced (e.g., API calls).</li><li>When failure due to timeout should propagate to parent coroutines.</li></ul><p><strong>withTimeoutOrNull</strong>:</p><ul><li>Non-critical operations where you can gracefully continue (e.g., optional retries).</li><li>When you want cleaner code without exception handling.</li></ul><h4>How does withTimeout handle cancellations in Kotlin Coroutines, and what are its effects on child coroutines, parent coroutines, and structured concurrency?</h4><p>In Kotlin Coroutines, <strong>withTimeout cancellations propagate to child coroutines through structured concurrency.</strong></p><p><strong>Parent-Child Relationship</strong>:</p><ul><li>withTimeout creates a coroutine scope for its block.</li><li>Any coroutine launched within this block becomes a <strong>child</strong> of the scope.</li></ul><p><strong>Cancellation Propagation</strong>:</p><ul><li>If the timeout is exceeded, withTimeout cancels the parent coroutine scope.</li><li>This cancellation propagates to all child coroutines in the scope, canceling them as well.</li></ul><p><strong>Exception Handling</strong>:</p><ul><li>The parent coroutine (withTimeout) throws a TimeoutCancellationException.</li><li>Child coroutines are canceled immediately and stop execution unless they handle the cancellation.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    try {<br>        withTimeout(1000L) {<br>            launch {<br>                repeat(5) { i -&gt;<br>                    println(&quot;Child coroutine: $i&quot;)<br>                    delay(300L) // Simulates a long-running task<br>                }<br>            }<br>            delay(1500L) // Exceeds timeout<br>        }<br>    } catch (e: TimeoutCancellationException) {<br>        println(&quot;Timeout occurred: ${e.message}&quot;)<br>    }<br>    println(&quot;Parent scope finished.&quot;)<br>}</pre><ul><li>The withTimeout block starts with a timeout of 1000ms.</li><li>A child coroutine is launched inside withTimeout.</li><li>The withTimeout exceeds its timeout (1000ms) and cancels itself.</li><li>The child coroutine is also canceled due to the propagation, and the parent scope finishes with a TimeoutCancellationException.</li></ul><h4>Key Points:</h4><ol><li>Cancellation is immediate and affects all child coroutines.</li><li>Children don’t complete unless explicitly handling cancellation.</li><li>Ensures all tasks in the timeout scope are cleaned up automatically.</li></ol><p><strong>Resource Cleanup</strong>:</p><ul><li>Ensuring proper cleanup using try-finally or invokeOnCompletion when a timeout occurs.</li></ul><p><strong>Nested Timeouts</strong>:</p><ul><li>Handling scenarios where multiple nested coroutines have independent or overlapping timeouts.</li></ul><p><strong>Timeout with Flow</strong>:</p><ul><li>Applying timeouts on a Flow using operators like onTimeout or custom mechanisms.</li></ul><p><strong>Custom Timeout Logic</strong>:</p><ul><li>Creating custom timeout mechanisms using select or Channel for finer control.</li></ul><p><strong>Integration with Dispatchers</strong>:</p><ul><li>Understanding the impact of timeouts on coroutine context (e.g., Dispatchers.IO or Dispatchers.Default).</li></ul><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ca21c56ff92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutine: Structured Concurrency & Scope Management]]></title>
            <link>https://medium.com/@guruprasadhegde4/coroutine-structured-concurrency-scope-management-a21962acb2ba?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21962acb2ba</guid>
            <category><![CDATA[scope-management]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 13:36:02 GMT</pubDate>
            <atom:updated>2024-11-22T13:36:02.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlAU6EyobyVlMza4MphmtA.png" /></figure><h4>What is Structured Concurrency?</h4><p>Structured concurrency in Kotlin ensures that the lifecycle of coroutines is tied to the scope in which they are launched. This approach simplifies coroutine management by introducing key rules and practices to avoid leaks, ensure clean cancellations, and handle errors effectively.</p><h4><strong>Key Concepts:</strong></h4><ol><li><strong>Hierarchical Lifecycle</strong>: Child coroutines depend on their parent’s lifecycle. If a parent is canceled, all its children are canceled too.</li><li><strong>CoroutineScope</strong>: Provides structured control over launching and canceling coroutines. It defines the scope in which coroutines operate.</li><li><strong>Context Propagation</strong>: Context (like dispatcher, job, or cancellation) flows naturally down the hierarchy.</li></ol><h4>1. Hierarchical Lifecycle</h4><p>In structured concurrency, child coroutines are tied to the lifecycle of their parent. If the parent scope is canceled, all its child coroutines are also canceled.</p><ul><li><strong>Automatic cancellation:</strong> When the parent is canceled, all its children are terminated.</li><li><strong>Error propagation:</strong> Exceptions from child coroutines propagate to the parent scope.</li></ul><pre>fun main() = runBlocking {<br>    val parentJob = launch {<br>        launch {<br>            repeat(5) { i -&gt;<br>                println(&quot;Child 1: Working on task $i&quot;)<br>                delay(200)<br>            }<br>        }<br><br>        launch {<br>            repeat(5) { i -&gt;<br>                println(&quot;Child 2: Working on task $i&quot;)<br>                delay(300)<br>            }<br>        }<br>    }<br><br>    delay(600) // Let the coroutines run for some time<br>    println(&quot;Cancelling parent...&quot;)<br>    parentJob.cancel() // Cancels all child coroutines automatically<br>}</pre><pre>Child 1: Working on task 0<br>Child 2: Working on task 0<br>Child 1: Working on task 1<br>Child 2: Working on task 1<br>Cancelling parent...</pre><p><em>All child coroutines stop immediately when the parent is canceled.</em></p><h4>2. CoroutineScope</h4><p>A <strong>CoroutineScope</strong> provides a structured environment for launching coroutines. It helps manage their lifecycle, ensuring they are properly canceled and cleaned up when the scope ends.</p><ul><li><strong>Scoped control:</strong> Coroutines launched in a scope automatically cancel when the scope ends.</li><li><strong>Reusable contexts:</strong> A single scope can launch multiple coroutines with shared context.</li></ul><pre>class MyViewModel : ViewModel() {<br>    private val scope = viewModelScope // Provided by Android&#39;s ViewModel<br><br>    fun fetchData() {<br>        scope.launch {<br>            val data = fetchDataFromNetwork()<br>            println(&quot;Fetched data: $data&quot;)<br>        }<br>    }<br><br>    private suspend fun fetchDataFromNetwork(): String {<br>        delay(1000) // Simulating network call<br>        return &quot;Sample Data&quot;<br>    }<br>}</pre><p>Here, the viewModelScope ensures that any launched coroutines are automatically canceled when the ViewModel is cleared.</p><h4>3. Context Propagation</h4><p>Structured concurrency ensures <strong>context propagation</strong>. The coroutine’s context (e.g., Job, Dispatcher, or Cancellation) flows from parent to child.</p><ul><li><strong>Shared dispatchers:</strong> Children inherit the dispatcher from the parent.</li><li><strong>Shared cancellation:</strong> Canceling the parent propagates cancellation to children.</li></ul><pre>fun main() = runBlocking {<br>    val parentContext = coroutineContext // Default context of runBlocking<br>    launch {<br>        println(&quot;Parent context: $coroutineContext&quot;)<br>        launch {<br>            println(&quot;Child context: $coroutineContext&quot;)<br>        }<br>    }<br>}</pre><pre>Parent context: [BlockingCoroutine{Active}@1, Dispatchers.Default]<br>Child context: [StandaloneCoroutine{Active}@2, Dispatchers.Default]</pre><p>The child coroutine inherits the <strong>job</strong> and <strong>dispatcher</strong> of the parent.</p><h4>Why Is This Important?</h4><ol><li><strong>Avoids Leaks:</strong> By tying coroutines to a scope, structured concurrency ensures no coroutine is left running when it shouldn’t be.</li><li><strong>Simplifies Cancellation:</strong> A single cancel() call propagates to all children, avoiding manual cleanup.</li><li><strong>Easier Debugging:</strong> Errors propagate in a predictable manner, making it easier to identify and fix issues.</li></ol><h4>What is Scope Management?</h4><p><strong>Scope management</strong> in Kotlin revolves around effectively organizing and controlling the lifecycle of coroutines using CoroutineScope.</p><ul><li><strong>Proper Cleanup</strong>: Coroutines are canceled when their associated scope is no longer valid (e.g., when an Activity is destroyed or a ViewModel is cleared).</li><li><strong>Error Containment</strong>: Errors in coroutines are managed to avoid unexpected crashes or side effects.</li><li><strong>Efficient Context Propagation</strong>: Ensures that coroutine contexts (like Dispatchers or cancellation signals) are passed down the hierarchy.</li></ul><h4>Key Concepts in Scope Management</h4><h4><strong>1. CoroutineScope :</strong></h4><ul><li>Defines the boundary within which coroutines operate.</li><li>Provides access to coroutine <strong>context</strong> and manages coroutine <strong>jobs</strong>.</li></ul><pre>val scope = CoroutineScope(Dispatchers.Main)<br><br>scope.launch {<br>    delay(1000)<br>    println(&quot;Running in scope&quot;)<br>}</pre><h4>2. Coroutine Context</h4><p>A set of configurations passed to a coroutine that defines:</p><ul><li><strong>Dispatcher</strong> (e.g., Dispatchers.Main, Dispatchers.IO).</li><li><strong>Job</strong>: Represents the lifecycle of the coroutine.</li><li><strong>Name</strong>: Optional debugging label.</li><li><strong>ExceptionHandler</strong>: Handles uncaught exceptions.</li></ul><pre>val scope = CoroutineScope(Dispatchers.IO + CoroutineName(&quot;MyCoroutine&quot;))<br>scope.launch {<br>    println(&quot;Running in IO dispatcher with name ${coroutineContext[CoroutineName]?.name}&quot;)<br>}</pre><h4>3. Job Hierarchy</h4><p><strong>Parent-Child Relationship</strong>: Coroutines inherit their parent’s job. Cancelling a parent cancels all its children.</p><pre>val parentScope = CoroutineScope(Dispatchers.Default)<br><br>parentScope.launch {<br>    launch {<br>        delay(2000)<br>        println(&quot;Child coroutine 1 completed&quot;)<br>    }<br><br>    launch {<br>        delay(3000)<br>        println(&quot;Child coroutine 2 completed&quot;)<br>    }<br><br>    println(&quot;Parent coroutine&quot;)<br>}<br><br>parentScope.cancel() // Cancels all coroutines in this scope.</pre><h4>4. Structured Concurrency</h4><ul><li>Ensures that coroutines are always launched within a scope, tying their lifecycle to the scope’s lifecycle.</li><li>Prevents orphaned or leaking coroutines.</li></ul><pre>suspend fun fetchData() = coroutineScope {<br>    launch {<br>        delay(1000)<br>        println(&quot;Fetching data&quot;)<br>    }<br><br>    launch {<br>        delay(500)<br>        println(&quot;Fetching additional data&quot;)<br>    }<br>}</pre><h4>Scope Management in Different Contexts</h4><h4>1. Android Scopes</h4><ul><li><strong>viewModelScope</strong>: Automatically cancels coroutines when the ViewModel is cleared.</li></ul><pre>class MyViewModel : ViewModel() {<br>    fun fetchData() {<br>        viewModelScope.launch {<br>            val result = fetchFromNetwork()<br>            println(&quot;Result: $result&quot;)<br>        }<br>    }<br>}</pre><ul><li><strong>lifecycleScope</strong>: Tied to an Activity/Fragment lifecycle. Automatically cancels coroutines when the lifecycle ends.</li></ul><pre>class MyActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        lifecycleScope.launch {<br>            println(&quot;Running with Activity&#39;s lifecycle&quot;)<br>        }<br>    }<br>}</pre><h4>2. Custom Scope</h4><ul><li>Create a custom scope for advanced lifecycle management.</li></ul><pre>class MyCustomScope : CoroutineScope {<br>    private val job = Job()<br>    override val coroutineContext = Dispatchers.Default + job<br><br>    fun stop() {<br>        job.cancel() // Cancels all coroutines in this scope.<br>    }<br>}<br><br>val customScope = MyCustomScope()<br><br>customScope.launch {<br>    delay(1000)<br>    println(&quot;Custom scope coroutine&quot;)<br>}<br><br>customScope.stop()</pre><h4>Handling Errors in Scope Management</h4><ol><li><strong>Default Behavior</strong>: Errors in child coroutines cancel the parent coroutine.</li></ol><pre>coroutineScope {<br>    launch {<br>        throw RuntimeException(&quot;Child failed!&quot;)<br>    }<br>    launch {<br>        println(&quot;This won&#39;t execute because the parent is canceled.&quot;)<br>    }<br>}</pre><p>2. <strong>Using </strong><strong>supervisorScope</strong>: Errors in one child coroutine do not cancel others.</p><pre>supervisorScope {<br>    launch {<br>        throw RuntimeException(&quot;Child failed!&quot;)<br>    }<br>    launch {<br>        delay(1000)<br>        println(&quot;This executes because supervisorScope isolates failures.&quot;)<br>    }<br>}</pre><h4>Best Practices for Scope Management</h4><ol><li><strong>Use Lifecycle-Aware Scopes</strong>:</li></ol><ul><li>Always prefer viewModelScope or lifecycleScope in Android to avoid leaks.</li></ul><p><strong>2. Avoid </strong><strong>GlobalScope</strong>:</p><ul><li>It’s not tied to any lifecycle and can lead to memory leaks.</li></ul><p><strong>3. Use Structured Concurrency</strong>:</p><ul><li>Always launch coroutines inside a scope to ensure proper cleanup.</li></ul><p><strong>4. Manage Exceptions Properly</strong>:</p><ul><li>Use try-catch, supervisorScope, or a custom CoroutineExceptionHandler for robust error handling.</li></ul><p><strong>5. Avoid Blocking Threads</strong>:</p><ul><li>Use Dispatchers.IO for long-running tasks like network calls or database operations.</li></ul><h4>If structured concurrency ensures proper lifecycle management of coroutines, why do we still need scope management in Kotlin?</h4><p>You’re right to observe that <strong>structured concurrency</strong> and <strong>scope management</strong> overlap in concept, but they are not entirely the same. Here’s why we need both</p><h4>1. What Structured Concurrency Does:</h4><ul><li><strong>Ensures Hierarchical Lifecycle</strong>: It ties coroutines to the lifecycle of their parent scope. If a parent is canceled, all child coroutines are canceled automatically.</li><li><strong>Error Propagation</strong>: Errors in child coroutines are propagated to their parent, ensuring proper exception handling.</li><li><strong>Cleaner Coroutine Management</strong>: It simplifies managing coroutines by enforcing logical relationships between coroutines (e.g., launching a child coroutine inside a scope).</li></ul><h4>2. What Scope Management Adds:</h4><ol><li><strong>Contextual Control</strong>: Scope management provides specific predefined scopes (GlobalScope, viewModelScope, lifecycleScope) tied to application components. This makes managing lifecycle-aware components easier.</li></ol><p><strong>2. Granularity</strong>: While structured concurrency enforces a general hierarchical lifecycle, scope management allows defining boundaries at an application-specific level. For instance:</p><ul><li>viewModelScope for a ViewModel</li><li>lifecycleScope for an Activity or Fragment</li></ul><p><strong>3. Integration with Components</strong>: Scope management integrates structured concurrency into Android and Kotlin constructs. This makes it easier to manage coroutines in real-world projects tied to UI lifecycles.</p><h4>Why Both Are Needed:</h4><ul><li><strong>Structured concurrency</strong> provides the <strong>conceptual framework</strong> to avoid leaks and handle lifecycle hierarchies.</li><li><strong>Scope management</strong> provides <strong>practical, component-specific tools</strong> that implement these principles for your codebase.</li></ul><pre>class MyViewModel : ViewModel() {<br>    // Scope management with viewModelScope<br>    fun fetchData() {<br>        viewModelScope.launch {<br>            // Structured concurrency in action: child coroutine<br>            launch {<br>                val result = fetchFromNetwork()<br>                println(result)<br>            }<br>            // Structured concurrency ensures this block waits for child coroutines<br>            println(&quot;All tasks completed&quot;)<br>        }<br>    }<br>}</pre><p>Here, viewModelScope (scope management) ties the coroutine lifecycle to the ViewModel, while the launch inside handles <strong>structured concurrency</strong> for child coroutines. Together, they provide clarity, safety, and integration with app lifecycles.</p><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21962acb2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: withContext()]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-coroutines-withcontext-cee08f44d1ca?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/cee08f44d1ca</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 14:16:45 GMT</pubDate>
            <atom:updated>2024-11-17T14:16:45.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MCFNPPP3Gj0ZO8j3h2mG7Q.jpeg" /></figure><p>withContext is a suspending function in Kotlin Coroutines that allows switching the coroutine&#39;s context (like a dispatcher) while suspending the execution of the current coroutine. It runs the given block of code in the specified context and returns its result. It doesn&#39;t create a new coroutine but temporarily changes the context for executing the code.</p><p><strong>Definition:</strong> withContext changes the coroutine&#39;s context to the specified dispatcher (or any other context) and ensures that once the block is done, it returns to the original context.</p><pre>val result = withContext(Dispatchers.IO) {<br>    // Perform a long-running task<br>    &quot;Task Result&quot;<br>}<br>// Execution returns to the original context after the block finishes</pre><ul><li>Switches context without launching a new coroutine.</li><li>Suspends the current coroutine until the block completes.</li><li>Ensures context switching for specific tasks like I/O operations.</li></ul><h4><strong>key characteristics of </strong><strong>withContext:</strong></h4><ul><li><strong>Context Switching</strong>: withContext is primarily used to change the coroutine&#39;s context, such as switching to a different Dispatcher (like Dispatchers.IO for I/O tasks or Dispatchers.Default for CPU-intensive tasks). This allows running certain parts of your code in a different thread pool without launching a new coroutine.</li></ul><pre>withContext(Dispatchers.IO) {<br>    // This code runs on the IO dispatcher (e.g., for file or network I/O)<br>}</pre><ul><li><strong>Suspension</strong>: When withContext is called, the current coroutine <strong>suspends</strong> execution and switches to the specified context to execute the given block of code. After the block completes, the coroutine <strong>resumes</strong> execution in the original context. This suspension happens without blocking the thread, making withContext efficient.</li></ul><pre>val data = withContext(Dispatchers.IO) {<br>    // Suspends while fetching data from the network<br>    fetchDataFromNetwork()<br>}<br>// Resumes in the original context once the network call is complete</pre><ul><li><strong>No New Coroutine</strong>: Unlike coroutine builders such as launch or async, which create and start new coroutines, withContext <strong>does not create a new coroutine</strong>. Instead, it reuses the current one, simply altering the execution context. This keeps the overhead low since there&#39;s no need to manage a separate coroutine lifecycle.</li></ul><pre>// Runs inside the same coroutine, no new coroutine is created<br>withContext(Dispatchers.Default) {<br>    // CPU-intensive work<br>}</pre><p><strong>How </strong><strong>withContext works internally under the hood ?</strong></p><pre>public suspend fun &lt;T&gt; withContext(<br>    context: CoroutineContext,<br>    block: suspend CoroutineScope.() -&gt; T<br>): T {<br>    contract {<br>        callsInPlace(block, InvocationKind.EXACTLY_ONCE)<br>    }<br>    return suspendCoroutineUninterceptedOrReturn sc@ { uCont -&gt;<br>        // compute new context<br>        val oldContext = uCont.context<br>        // Copy CopyableThreadContextElement if necessary<br>        val newContext = oldContext.newCoroutineContext(context)<br>        // always check for cancellation of new context<br>        newContext.ensureActive()<br>        // FAST PATH #1 -- new context is the same as the old one<br>        if (newContext === oldContext) {<br>            val coroutine = ScopeCoroutine(newContext, uCont)<br>            return@sc coroutine.startUndispatchedOrReturn(coroutine, block)<br>        }<br>        // FAST PATH #2 -- the new dispatcher is the same as the old one (something else changed)<br>        // `equals` is used by design (see equals implementation is wrapper context like ExecutorCoroutineDispatcher)<br>        if (newContext[ContinuationInterceptor] == oldContext[ContinuationInterceptor]) {<br>            val coroutine = UndispatchedCoroutine(newContext, uCont)<br>            // There are changes in the context, so this thread needs to be updated<br>            withCoroutineContext(coroutine.context, null) {<br>                return@sc coroutine.startUndispatchedOrReturn(coroutine, block)<br>            }<br>        }<br>        // SLOW PATH -- use new dispatcher<br>        val coroutine = DispatchedCoroutine(newContext, uCont)<br>        block.startCoroutineCancellable(coroutine, coroutine)<br>        coroutine.getResult()<br>    }<br>}</pre><p><strong>Function Signature:</strong></p><pre>public suspend fun &lt;T&gt; withContext(<br>    context: CoroutineContext,<br>    block: suspend CoroutineScope.() -&gt; T<br>): T</pre><ul><li><strong>context: CoroutineContext</strong>: This parameter specifies the new coroutine context (e.g., dispatcher or additional context elements) in which the provided block will execute.</li><li><strong>block: suspend CoroutineScope.() -&gt; T</strong>: This is the suspending lambda block of code that will be executed in the new context.</li><li><strong>&lt;T&gt;</strong>: The block returns a value of type T, and this result will be returned by withContext.</li></ul><p><strong>Contract: Ensure the Block is Called Exactly Once:</strong></p><pre>contract {<br>    callsInPlace(block, InvocationKind.EXACTLY_ONCE)<br>}</pre><ul><li>The contract enforces that the block will be called exactly once, helping with optimization (for things like inlining or ensuring side-effects occur only once).</li></ul><p><strong>Suspending the Coroutine:</strong></p><pre>return suspendCoroutineUninterceptedOrReturn sc@ { uCont -&gt;</pre><ul><li><strong>suspendCoroutineUninterceptedOrReturn</strong>: This low-level function suspends the current coroutine. The lambda inside is responsible for handling the continuation (uCont), which is how the coroutine will be resumed later.</li><li><strong>uCont (continuation)</strong>: Represents the state of the suspended coroutine, allowing it to be resumed after the withContext block finishes executing.</li></ul><p><strong>Get the Old and New Contexts:</strong></p><pre>val oldContext = uCont.context<br>val newContext = oldContext.newCoroutineContext(context)</pre><ul><li><strong>oldContext</strong>: The current coroutine&#39;s context, before switching to the new one.</li><li><strong>newContext</strong>: This is the <strong>combined</strong> context, merging the current oldContext with the new one passed to withContext. The new context may include things like a new dispatcher or thread-local variables.</li></ul><p><strong>Ensure the New Context is Active:</strong></p><pre>newContext.ensureActive()</pre><ul><li><strong>ensureActive()</strong>: Before proceeding, the function checks if the new context is still active (i.e., the coroutine hasn&#39;t been canceled). If the new context is canceled, this will throw a CancellationException.</li></ul><p><strong>Fast Path 1 — Contexts are the Same:</strong></p><pre>if (newContext === oldContext) {<br>    val coroutine = ScopeCoroutine(newContext, uCont)<br>    return@sc coroutine.startUndispatchedOrReturn(coroutine, block)<br>}</pre><ul><li>If the <strong>new context is exactly the same as the old one</strong> (e.g., no changes in the dispatcher or other context elements), the block is executed without any additional overhead.</li><li><strong>ScopeCoroutine</strong>: This creates a coroutine without changing the dispatcher. It’s used when no context switch is necessary.</li><li><strong>startUndispatchedOrReturn</strong>: Executes the block in the <strong>same context</strong> without dispatching to a different thread or thread pool.</li></ul><p><strong>Fast Path 2 — Same Dispatcher but Different Context Elements:</strong></p><pre>if (newContext[ContinuationInterceptor] == oldContext[ContinuationInterceptor]) {<br>    val coroutine = UndispatchedCoroutine(newContext, uCont)<br>    withCoroutineContext(coroutine.context, null) {<br>        return@sc coroutine.startUndispatchedOrReturn(coroutine, block)<br>    }<br>}</pre><ul><li>If the <strong>dispatcher (thread handling the execution) hasn’t changed</strong> but other context elements have (like job or other context-related metadata), it uses UndispatchedCoroutine to run the block in the <strong>same thread</strong> without a thread switch.</li><li><strong>withCoroutineContext</strong>: This function temporarily updates the current thread’s context to reflect the new context while executing the block. Once the block is done, it reverts back to the original context.</li></ul><p><strong>Slow Path — New Dispatcher:</strong></p><pre>val coroutine = DispatchedCoroutine(newContext, uCont)<br>block.startCoroutineCancellable(coroutine, coroutine)<br>coroutine.getResult()</pre><ul><li><strong>New Dispatcher</strong>: If the dispatcher has changed (e.g., switching from Dispatchers.Default to Dispatchers.IO), it follows the &quot;slow path&quot; where a new dispatcher (thread pool) is used.</li><li><strong>DispatchedCoroutine</strong>: This is used to dispatch the coroutine to a new dispatcher (i.e., a different thread or thread pool) and execute the block there.</li><li><strong>startCoroutineCancellable</strong>: Starts the execution of the block, but in a way that can be canceled (since coroutines should be able to handle cancellation).</li><li><strong>getResult()</strong>: This suspends the coroutine until the result is available (i.e., until the block finishes executing in the new context).</li></ul><p><strong>Return the Result:</strong></p><ul><li>Once the block completes, withContext returns the result from the block (T), resuming the coroutine from where it was suspended.</li></ul><p><strong>Summary of Steps:</strong></p><ol><li><strong>Check the current and new contexts</strong>: Determine if there’s a need to switch contexts.</li><li><strong>Cancellation Check</strong>: Ensure the new context is active (not canceled).</li><li><strong>Fast Path 1</strong>: If contexts are identical, run the block in the current context without creating new coroutines.</li><li><strong>Fast Path 2</strong>: If the dispatcher is the same but the context changed, run the block without switching threads.</li><li><strong>Slow Path</strong>: If the dispatcher changed, switch to a new dispatcher (different thread or pool) and run the block.</li><li><strong>Return Result</strong>: Once the block is complete, the coroutine resumes with the result.</li></ol><p><strong>How Dispatchers Are Helpful in </strong><strong>withContext</strong></p><p>Dispatchers are critical in withContext as they define the thread or thread pool where the coroutine runs</p><p><strong>1. Efficient Thread Management</strong></p><ul><li><strong>What It Does</strong>: Dispatchers prevent blocking the main thread, ensuring smooth application performance.</li><li><strong>How It Helps</strong>: You can shift heavy or long-running tasks (e.g., I/O or computation) to appropriate background threads.</li></ul><pre>withContext(Dispatchers.IO) {<br>    // Prevents blocking the main thread during a network call<br>    performNetworkOperation()<br>}</pre><p><strong>2. Improves Readability and Structure</strong></p><ul><li><strong>What It Does</strong>: Clearly separates concerns by assigning specific contexts for tasks (e.g., UI updates, I/O operations).</li><li><strong>How It Helps</strong>: Enhances code readability and ensures tasks run in their appropriate thread.</li></ul><pre>withContext(Dispatchers.Main) {<br>    updateUI()  // UI-related task<br>}<br>withContext(Dispatchers.IO) {<br>    fetchDataFromDatabase()  // I/O task<br>}</pre><p><strong>3. Performance Optimization</strong></p><ul><li><strong>What It Does</strong>: Matches task types to optimized thread pools.</li><li><strong>How It Helps</strong>: Maximizes CPU and thread utilization without overloading any single thread.</li></ul><pre>val result = withContext(Dispatchers.Default) {<br>    heavyComputationTask() // Uses optimal CPU cores<br>}</pre><p><strong>Key Points to Remember</strong></p><ol><li><strong>Thread-Safe Operations</strong>: Avoids accessing shared resources directly from the main thread.</li><li><strong>Structured Concurrency</strong>: Ensures the coroutine’s context remains linked to its parent.</li><li><strong>Reduced Boilerplate</strong>: Simplifies threading logic compared to manual thread management.</li></ol><p><strong>Comparison of </strong><strong>withContext, </strong><strong>launch, and </strong><strong>async</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*4W1RveHwhqvRBRbRZCR4Rw.png" /></figure><p><strong>Key Differences</strong></p><ol><li><strong>Execution Behavior</strong>:</li></ol><ul><li>withContext: Suspends the current coroutine and executes sequentially in the new context.</li><li>launch/async: Launches concurrent coroutines.</li></ul><ol><li><strong>Result Handling</strong>:</li></ol><ul><li>withContext: Directly returns the result.</li><li>launch: No direct result, just a Job to track.</li><li>async: Provides a Deferred&lt;T&gt; for retrieving the result later using await().</li></ul><p><strong>When to Use What?</strong></p><ul><li><strong>withContext</strong>: For sequential tasks where you need the result immediately (e.g., switching to I/O or computation context).</li><li><strong>launch</strong>: For background tasks that don’t need a result (e.g., logging or notifications).</li><li><strong>async</strong>: For parallel tasks where results are required (e.g., aggregating data).</li></ul><p><strong>Exception Handling with </strong><strong>withContext</strong></p><p>withContext propagates exceptions to the parent coroutine, ensuring proper handling and maintaining structured concurrency.</p><p><strong>Key Points</strong></p><ol><li><strong>Automatic Propagation</strong>: If an exception occurs, it is thrown to the parent coroutine for handling.</li><li><strong>try-catch for Safe Handling</strong>: Use try-catch within withContext to manage exceptions locally.</li><li><strong>Context-Specific Handling</strong>: Handle exceptions differently based on the dispatcher or task context.</li></ol><p><strong>Real-World Use Case: Local Exception Handling with </strong><strong>withContext</strong></p><pre>import kotlinx.coroutines.*<br><br>fun fetchUserData() = runBlocking {<br>    try {<br>        val userData = withContext(Dispatchers.IO) {<br>            fetchFromServer() // Simulated network call<br>        }<br>        println(&quot;User data fetched: $userData&quot;)<br>    } catch (e: Exception) {<br>        println(&quot;Error fetching user data: ${e.message}&quot;)<br>        // Show an error message to the user, e.g., &quot;Network request failed&quot;<br>    }<br>}<br><br>// Simulated server function<br>suspend fun fetchFromServer(): String {<br>    delay(1000) // Simulate network delay<br>    throw Exception(&quot;Network timeout&quot;) // Simulate failure<br>}</pre><p><strong>Real-World Use Case: Propagation to Parent with </strong><strong>withContext</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val parentJob = launch {<br>        try {<br>            processPayment()<br>        } catch (e: Exception) {<br>            println(&quot;Payment failed: ${e.message}&quot;)<br>            // Show a global error message to the user<br>        }<br>    }<br>    parentJob.join()<br>    println(&quot;End of payment process.&quot;)<br>}<br><br>suspend fun processPayment() {<br>    withContext(Dispatchers.IO) {<br>        println(&quot;Validating payment details...&quot;)<br>        validatePayment() // May throw an exception<br>    }<br><br>    withContext(Dispatchers.Default) {<br>        println(&quot;Processing transaction...&quot;)<br>        processTransaction() // May throw an exception<br>    }<br><br>    withContext(Dispatchers.IO) {<br>        println(&quot;Sending confirmation...&quot;)<br>        sendConfirmation() // May throw an exception<br>    }<br>}<br><br>fun validatePayment() {<br>    throw IllegalArgumentException(&quot;Invalid payment details&quot;)<br>}<br><br>fun processTransaction() {<br>    // Simulate transaction processing<br>}<br><br>fun sendConfirmation() {<br>    // Simulate sending confirmation<br>}</pre><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cee08f44d1ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: runBlocking coroutine builder]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-coroutines-runblocking-coroutine-builder-2b818462e79b?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b818462e79b</guid>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine-context]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 03:44:34 GMT</pubDate>
            <atom:updated>2024-10-15T04:09:14.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJIkM7sxLoXRyLGr-eDU2A.png" /></figure><p>Here are the topics on the <strong>runBlocking </strong>coroutine builder</p><blockquote><strong><em>What are the coroutine builders in Kotlin?</em></strong></blockquote><blockquote><strong><em>Key Characteristics of the </em></strong><strong>runBlocking <em>Builder</em></strong></blockquote><blockquote><strong><em>How the </em></strong><strong><em>runBlocking function manages the coroutine context and event loops internally? Under the hood</em></strong></blockquote><blockquote><strong><em>When using </em></strong><strong><em>runBlocking, does the coroutine execution run on the same thread that called </em></strong><strong><em>runBlocking, or does it switch to a different thread?</em></strong></blockquote><blockquote><strong><em>How Exceptions Work in </em></strong><strong>runBlocking</strong><strong><em>:</em></strong></blockquote><blockquote><strong><em>Some important question and answer on </em></strong><strong><em>runBlocking</em></strong></blockquote><p>Coroutine builders are functions which is used to create a coroutine. It can be called from normal functions because they do not suspend themselves. They act as a link between the suspending and non-suspending parts of our code.</p><p><strong>What are the coroutine builders in Kotlin?</strong></p><p>In Kotlin, <strong>coroutine builders</strong> are functions that allow you to create and start coroutines. The main coroutine builders are</p><p><strong>launch</strong>:</p><ul><li>Starts a new coroutine and doesn’t return any result.</li><li>Often used for fire-and-forget tasks, where you don’t need a result.</li></ul><pre>GlobalScope.launch {<br>    // Background task<br>}</pre><p><strong>async</strong>:</p><ul><li>Starts a new coroutine and returns a <strong>Deferred</strong> object, which allows you to retrieve a result later.</li><li>Useful for parallel computations when you need a result.</li></ul><pre>val result = GlobalScope.async {<br>    // Some computation<br>    42<br>}<br>println(result.await()) // Waits for the result</pre><p><strong>withContext</strong>:</p><ul><li>Changes the context of an already running coroutine (e.g., switching to Dispatchers.IO for I/O operations).</li><li>Does not start a new coroutine but modifies the execution context.</li></ul><pre>GlobalScope.launch {<br>    val data = withContext(Dispatchers.IO) {<br>        // Perform I/O operations<br>        &quot;Fetched data&quot;<br>    }<br>    println(data)<br>}</pre><p><strong>runBlocking</strong>:</p><ul><li>Starts a coroutine that blocks the current thread until it completes. Used in main functions or tests to bridge regular code with coroutines.</li></ul><pre>runBlocking {<br>    // Coroutine inside a blocking call<br>    delay(1000)<br>    println(&quot;Done&quot;)<br>}</pre><p>These builders help manage how coroutines are launched and controlled within different contexts and scopes.</p><p><strong>The </strong><strong>runBlocking coroutine builder:</strong></p><p>runBlocking is a coroutine builder that <strong>blocks the current thread</strong> while executing a coroutine until its completion. It is mainly used for <strong>bridging blocking code</strong> with coroutines, especially in <strong>main functions</strong> and <strong>tests</strong> where suspending functions need to be called.</p><p><strong>Key characteristics of </strong><strong>runBlocking:</strong></p><ul><li><strong>Blocks the current thread</strong>: Unlike other coroutine builders, runBlocking freezes the thread it&#39;s called on until the coroutine inside completes. This is different from non-blocking coroutines like launch and async, which allow the thread to continue working while the coroutine executes in the background.</li></ul><pre>fun main() = runBlocking {<br>    // The main thread is blocked here until the coroutine finishes<br>    println(&quot;Start&quot;)<br>    delay(1000) // Suspends the coroutine but blocks the thread<br>    println(&quot;End&quot;)<br>}</pre><ul><li><strong>Bridges blocking and non-blocking code</strong>: runBlocking is mostly used in environments where suspending functions can&#39;t normally be called, like main functions or unit tests. It allows you to run coroutines in these contexts by synchronously waiting for their completion</li></ul><pre>fun main() = runBlocking {<br>    // Can use suspend functions in blocking code<br>    doWork()  // Suspend function<br>}<br><br>suspend fun doWork() {<br>    delay(500)<br>    println(&quot;Work done!&quot;)<br>}</pre><ul><li><strong>Runs a coroutine</strong>: runBlocking runs a coroutine, just like launch or async, but with the difference that it waits for the coroutine to finish before proceeding. This makes it useful when you need coroutine-based code to complete before moving on.</li></ul><pre>fun main() = runBlocking {<br>    val result = calculate()  // A coroutine that returns a result<br>    println(&quot;Result: $result&quot;) // Prints after calculation is done<br>}<br><br>suspend fun calculate(): Int {<br>    delay(1000)<br>    return 42<br>}</pre><p><strong>How the </strong><strong>runBlocking function manages the coroutine context and event loops internally? Under the hood.</strong></p><p><strong>Function Signature</strong></p><pre>public actual fun &lt;T&gt; runBlocking(context: CoroutineContext, block: suspend CoroutineScope.() -&gt; T): T {<br>    contract {<br>        callsInPlace(block, InvocationKind.EXACTLY_ONCE)<br>    }<br>    val currentThread = Thread.currentThread()<br>    val contextInterceptor = context[ContinuationInterceptor]<br>    val eventLoop: EventLoop?<br>    val newContext: CoroutineContext<br>    if (contextInterceptor == null) {<br>        // create or use private event loop if no dispatcher is specified<br>        eventLoop = ThreadLocalEventLoop.eventLoop<br>        newContext = GlobalScope.newCoroutineContext(context + eventLoop)<br>    } else {<br>        // See if context&#39;s interceptor is an event loop that we shall use (to support TestContext)<br>        // or take an existing thread-local event loop if present to avoid blocking it (but don&#39;t create one)<br>        eventLoop = (contextInterceptor as? EventLoop)?.takeIf { it.shouldBeProcessedFromContext() }<br>            ?: ThreadLocalEventLoop.currentOrNull()<br>        newContext = GlobalScope.newCoroutineContext(context)<br>    }<br>    val coroutine = BlockingCoroutine&lt;T&gt;(newContext, currentThread, eventLoop)<br>    coroutine.start(CoroutineStart.DEFAULT, coroutine, block)<br>    return coroutine.joinBlocking()<br>}</pre><pre>public actual fun &lt;T&gt; runBlocking(<br>    context: CoroutineContext, <br>    block: suspend CoroutineScope.() -&gt; T<br>): T</pre><ul><li><strong>context: CoroutineContext</strong>: This is the coroutine&#39;s context, which can specify things like the dispatcher (i.e., on which thread the coroutine should run) or other coroutine-related configurations.</li><li><strong>block: suspend CoroutineScope.() -&gt; T</strong>: This is the suspendable code block that you want to execute in the coroutine.</li><li><strong>Returns</strong>: The result T from the coroutine block once it finishes.</li></ul><p><strong>Contract</strong></p><pre>contract {<br>    callsInPlace(block, InvocationKind.EXACTLY_ONCE)<br>}</pre><p>This <strong>contract</strong> ensures that the block will be called exactly once. Contracts in Kotlin are used to provide information to the compiler about how a function will behave.</p><p>Thread and Context Setup</p><pre>val currentThread = Thread.currentThread()<br>val contextInterceptor = context[ContinuationInterceptor]<br>val eventLoop: EventLoop?<br>val newContext: CoroutineContext</pre><ul><li><strong>currentThread</strong>: Captures the current thread where runBlocking is invoked, since runBlocking will block this thread.</li><li><strong>contextInterceptor</strong>: Extracts the ContinuationInterceptor from the context, which can be a Dispatcher (such as Dispatchers.Default or Dispatchers.IO).</li><li><strong>eventLoop</strong> and <strong>newContext</strong>: These will be used to manage the coroutine’s execution context (whether it&#39;s an event loop or some other dispatcher).</li></ul><p><strong>Event Loop and Context Handling</strong></p><p>There are two scenarios handled here, based on whether a ContinuationInterceptor (such as a dispatcher) is present in the coroutine context.</p><p><em>No Dispatcher Specified (No </em><em>contextInterceptor)</em></p><pre>if (contextInterceptor == null) {<br>    eventLoop = ThreadLocalEventLoop.eventLoop<br>    newContext = GlobalScope.newCoroutineContext(context + eventLoop)<br>}</pre><ul><li>If no dispatcher is provided, the function creates or retrieves an <strong>event loop</strong> from the thread-local storage using ThreadLocalEventLoop.eventLoop. This event loop will control the coroutine’s execution.</li><li>A new coroutine context is created by combining the given context with this event loop.</li></ul><p><em>Dispatcher Specified (With </em><em>contextInterceptor)</em></p><pre>else {<br>    eventLoop = (contextInterceptor as? EventLoop)?.takeIf { it.shouldBeProcessedFromContext() }<br>        ?: ThreadLocalEventLoop.currentOrNull()<br>    newContext = GlobalScope.newCoroutineContext(context)<br>}</pre><ul><li>If a ContinuationInterceptor (like a dispatcher) is provided, the function checks if it&#39;s an event loop that should be processed or retrieves any thread-local event loop if one exists.</li><li>A new coroutine context is created using the provided context.</li></ul><p><strong>Coroutine Creation</strong></p><pre>val coroutine = BlockingCoroutine&lt;T&gt;(newContext, currentThread, eventLoop)</pre><p>A BlockingCoroutine&lt;T&gt; is created. This special coroutine will execute the given block in a <strong>blocking manner</strong>, using the newContext created earlier and managing the currentThread and eventLoop.</p><p><strong>Starting the Coroutine</strong></p><pre>coroutine.start(CoroutineStart.DEFAULT, coroutine, block)</pre><ul><li>The coroutine is started using the start function. Here, the coroutine uses the DEFAULT start mode, meaning it begins execution immediately (though other start modes like LAZY exist).</li><li>The block of code passed to runBlocking is then executed within this coroutine.</li></ul><p><strong>Blocking the Thread Until Completion</strong></p><pre>return coroutine.joinBlocking()</pre><p>This is where the actual <strong>blocking</strong> happens. joinBlocking() will block the current thread (where runBlocking was called) until the coroutine completes its execution and returns the result.</p><p><strong>Summary of Internal Working:</strong></p><blockquote><strong>Thread and context</strong>: The function captures the current thread and checks if a dispatcher or event loop is provided in the coroutine context.</blockquote><blockquote><strong>Event loop</strong>: If no dispatcher is provided, it creates or retrieves an event loop. If a dispatcher is available, it checks whether it is also an event loop or uses a thread-local event loop if available.</blockquote><blockquote><strong>Coroutine creation</strong>: A special BlockingCoroutine is created with the provided context and event loop.</blockquote><blockquote><strong>Execution</strong>: The coroutine is started, and the calling thread is blocked until the coroutine completes.</blockquote><blockquote><strong>Blocking behavior</strong>: Finally, the result of the coroutine is returned after blocking the thread during execution.</blockquote><p><strong>When using </strong><strong>runBlocking, does the coroutine execution run on the same thread that called </strong><strong>runBlocking, or does it switch to a different thread?</strong></p><p>Once runBlocking blocks the thread, the coroutine <strong>runs on the same thread</strong> where runBlocking was called. It doesn&#39;t switch to a different thread unless a specific dispatcher (like Dispatchers.IO or Dispatchers.Default) is explicitly provided.</p><p>By default, runBlocking executes everything in the <strong>current thread</strong>, blocking it until the coroutine completes. If a dispatcher is provided in the coroutine context, the coroutine block may be dispatched to a different thread, but the calling thread will still be blocked until completion.</p><pre>import kotlinx.coroutines.*<br><br>fun main() {<br>    println(&quot;Main thread: ${Thread.currentThread().name}&quot;)<br><br>    runBlocking {<br>        // This runs on the same thread as runBlocking<br>        println(&quot;Inside runBlocking: ${Thread.currentThread().name}&quot;)<br><br>        // Launching a coroutine with no dispatcher specified (same thread)<br>        launch {<br>            println(&quot;Inside launch with no dispatcher: ${Thread.currentThread().name}&quot;)<br>        }<br><br>        // Launching a coroutine with Dispatchers.Default (runs on a different thread)<br>        launch(Dispatchers.Default) {<br>            println(&quot;Inside launch with Dispatchers.Default: ${Thread.currentThread().name}&quot;)<br>        }<br>    }<br><br>    println(&quot;Back to main thread: ${Thread.currentThread().name}&quot;)<br>}<br><br>// Output of the program<br>Main thread: main<br>Inside runBlocking: main<br>Inside launch with no dispatcher: main<br>Inside launch with Dispatchers.Default: DefaultDispatcher-worker-1<br>Back to main thread: main</pre><ul><li>The runBlocking coroutine runs on the <strong>main thread</strong>.</li><li>The first launch (without a dispatcher) runs on the same thread (main).</li><li>The second launch, using Dispatchers.Default, runs on a <strong>different thread</strong> (DefaultDispatcher-worker-1).</li><li>After runBlocking finishes, the program returns to the main thread</li></ul><p><strong>How cancellation work in </strong><strong>runBlocking:</strong></p><p><strong>Cooperative Cancellation</strong>:</p><ul><li>Coroutines are designed to be cancellable. When you call cancel() on a coroutine&#39;s job, the coroutine will stop executing at the next <strong>suspension point</strong> (like delay(), yield(), etc.). If it is not at a suspension point, it will continue until it reaches one.</li></ul><p><strong>How Cancellation Works</strong>:</p><ul><li>When you use runBlocking, it creates a coroutine scope. If you cancel any coroutine launched in this scope, the runBlocking function can also be affected by this cancellation.</li><li>Once cancelled, the coroutine will terminate and will not continue executing further.</li></ul><p><strong>Immediate Cancellation</strong>:</p><ul><li>If a coroutine is currently executing and is not at a suspension point, it will not stop immediately. However, it will throw a CancellationException at the next suspension point.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    // Launch a coroutine in the runBlocking scope<br>    val job = launch {<br>        repeat(10) { i -&gt;<br>            println(&quot;Job: I&#39;m working on $i ...&quot;)<br>            // Simulate work with delay (suspension point)<br>            delay(100) <br>        }<br>    }<br><br>    delay(250) // Let the job run for a bit<br>    println(&quot;Main: I&#39;m tired of waiting!&quot;)<br>    job.cancel() // Cancel the job<br>    job.join()   // Wait for the job to complete<br><br>    println(&quot;Main: Now I can quit.&quot;)<br>}<br></pre><p><strong>Coroutine Scope</strong>:</p><ul><li>The runBlocking function creates a coroutine scope and starts running the code inside it.</li></ul><p><strong>Launching the Coroutine</strong>:</p><ul><li>Inside this scope, a coroutine is launched using launch. It will print messages in a loop, simulating some work with delay(100), which acts as a suspension point.</li></ul><p><strong>Main Thread Delay</strong>:</p><ul><li>The main coroutine waits for 250 milliseconds before proceeding. This allows the launched coroutine to run for a short period.</li></ul><p><strong>Cancelling the Job</strong>:</p><ul><li>After the delay, the main coroutine calls job.cancel(), which cancels the launched coroutine.</li><li>Since the coroutine was running a loop and at the next suspension point (delay(100)), it will stop executing after printing a few messages.</li></ul><p><strong>Joining the Job</strong>:</p><ul><li>The join() function is called to wait for the coroutine to complete after cancellation.</li></ul><pre><br>Job: I&#39;m working on 0 ...<br>Job: I&#39;m working on 1 ...<br>Job: I&#39;m working on 2 ...<br>Main: I&#39;m tired of waiting!<br>Main: Now I can quit.</pre><ul><li>The coroutine started by launch prints a few messages before the main coroutine cancels it.</li><li>After the main coroutine calls job.cancel(), the launched coroutine will stop at its next suspension point.</li><li>The main function waits for the coroutine to finish (even if it’s cancelled) before it exits.</li></ul><ol><li><strong>What is the purpose of </strong><strong>runBlocking, and when should it be used?</strong></li></ol><p>runBlocking is a coroutine builder designed to <strong>bridge regular blocking code</strong> and coroutine-based code. It starts a coroutine and <strong>blocks the current thread</strong> until all the work inside the coroutine scope completes. It is typically used in <strong>testing</strong> or when you need to integrate suspending code into a <strong>non-coroutine context</strong>, like the main function of a Kotlin application or unit tests where you want to block the main thread for the coroutine’s completion.</p><p>However, it is <strong>not recommended</strong> for regular coroutine usage in Android apps or servers because blocking threads goes against the non-blocking nature of coroutines.</p><p><strong>2. How does </strong><strong>runBlocking manage thread blocking and coroutine execution?</strong></p><p>runBlocking creates a <strong>synchronous coroutine</strong> and blocks the calling thread (like the main thread) until the coroutine completes. This blocking happens by using an internal event loop that simulates blocking. It schedules coroutine tasks to be executed in the current thread and waits until they finish.</p><ul><li>If no dispatcher is provided, it runs on the current thread.</li><li>If a dispatcher (e.g., Dispatchers.IO, Dispatchers.Default) is provided, the coroutine executes on a different thread, but the calling thread will remain blocked until the coroutine completes.</li></ul><p><strong>3. What is the difference between </strong><strong>runBlocking and </strong><strong>launch or </strong><strong>async?</strong></p><ul><li><strong>runBlocking</strong> blocks the current thread and waits for the coroutine to complete. It&#39;s typically used in non-coroutine contexts where you need to wait for coroutine execution (e.g., the main function).</li><li><strong>launch</strong> is non-blocking and returns a Job. It doesn&#39;t block the thread; instead, it runs the coroutine asynchronously and returns immediately, allowing other tasks to continue.</li><li><strong>async</strong> is similar to launch but returns a Deferred result, allowing you to retrieve the coroutine’s result using await(). It’s used when you need a result from a coroutine.</li></ul><p><strong>4. How does </strong><strong>runBlocking handle cancellation, and what are the limitations?</strong></p><p>runBlocking follows the <strong>cooperative cancellation model</strong> of coroutines. If a coroutine inside runBlocking is cancelled (via job.cancel()), it will throw a CancellationException at the next <strong>suspension point</strong> (e.g., delay(), yield()). However, if the coroutine is executing code that doesn&#39;t have suspension points (like a tight loop), it won&#39;t cancel immediately.</p><p><strong>Limitation</strong>: If a coroutine inside runBlocking doesn&#39;t check for cancellation regularly (i.e., no suspension points), the cancellation won&#39;t be immediate. You may need to manually call isActive or ensureActive() to ensure proper cancellation.</p><p><strong>5. What happens if an exception is thrown inside </strong><strong>runBlocking?</strong></p><p>If an <strong>exception</strong> is thrown inside runBlocking, it will propagate up to the calling thread, and the entire runBlocking scope will be cancelled. This behavior is similar to any other coroutine builder where unhandled exceptions are propagated to the parent scope.</p><p>For example, in the main function, if an exception occurs in runBlocking, it will terminate the program unless the exception is caught or handled within a try-catch block.</p><p><strong>6. How does </strong><strong>runBlocking interact with different Coroutine Dispatchers (e.g., </strong><strong>Dispatchers.Main, </strong><strong>Dispatchers.IO)?</strong></p><p>By default, runBlocking runs on the <strong>current thread</strong>, but you can change its behavior by passing a specific dispatcher via the context parameter. This allows you to control where the coroutine’s work is executed:</p><ul><li><strong>Dispatchers.Main</strong>: Runs on the <strong>main thread</strong> (mostly used in Android to run UI tasks).</li><li><strong>Dispatchers.IO</strong>: Runs on a pool of threads optimized for <strong>I/O-bound operations</strong> (e.g., network or database operations).</li><li><strong>Dispatchers.Default</strong>: Uses a shared pool of threads for <strong>CPU-intensive tasks</strong>.</li></ul><p>Despite using a different dispatcher, the thread that called runBlocking will still be blocked until the coroutine finishes.</p><p><strong>7. How does </strong><strong>runBlocking differ from </strong><strong>runBlockingTest in Kotlin coroutines testing?</strong></p><ul><li><strong>runBlocking</strong>: It is a coroutine builder for real coroutine code, blocking the current thread while the coroutine executes. It is designed for real-time execution and should only be used in production code when necessary.</li><li><strong>runBlockingTest</strong>: It is specifically for <strong>testing coroutines</strong>. It <strong>does not block threads</strong> in real-time but instead <strong>advances time</strong> automatically to allow faster testing of suspending functions without actual delays. This function is part of the Kotlin coroutines testing library and should only be used in unit tests.</li></ul><p>runBlockingTest is designed to be faster than runBlocking and is more suitable for coroutine-based test cases.</p><p><strong>8. Is </strong><strong>runBlocking thread-safe? Can it be used in a multi-threaded environment?</strong></p><p><strong>Answer</strong>: Yes, runBlocking is thread-safe. However, it is generally not recommended for multi-threaded environments, especially in Android or server applications, because it <strong>blocks the current thread</strong>, which is contrary to the non-blocking philosophy of coroutines.</p><p>In multi-threaded applications, it’s better to use <strong>non-blocking coroutine builders</strong> like launch or async in combination with appropriate dispatchers (e.g., Dispatchers.IO, Dispatchers.Default).</p><p><strong>9. Why should </strong><strong>runBlocking not be used in production Android code?</strong></p><p>In Android, runBlocking should be avoided in production because:</p><ul><li>It <strong>blocks the main thread</strong>, causing <strong>UI freezes</strong> and an unresponsive app.</li><li>Android development encourages <strong>non-blocking</strong> code execution to keep the UI thread responsive. Coroutines with launch and appropriate dispatchers (Dispatchers.IO for I/O operations or Dispatchers.Default for CPU-bound tasks) are preferred to achieve this.</li></ul><p>Instead, use launch with Dispatchers.Main for UI updates and background threads for non-UI work.</p><p><strong>10. What happens when </strong><strong>runBlocking is used in a nested coroutine context?</strong></p><p><strong>Answer</strong>: When runBlocking is used inside another coroutine context (which is rare but can happen), it <strong>blocks the thread of the outer coroutine</strong> until its execution completes. This defeats the purpose of non-blocking coroutines, making the parent coroutine wait unnecessarily.</p><p>Nested runBlocking calls are generally discouraged because they can lead to thread blocking and performance issues. Instead, you should rely on non-blocking coroutine builders like launch and async.</p><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b818462e79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: ‘async’ coroutine builder]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-coroutines-async-coroutine-builder-a32b6dda3bf3?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a32b6dda3bf3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[buidler]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 09:45:07 GMT</pubDate>
            <atom:updated>2024-10-15T04:17:07.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yDDUZU4S2X0WMtxD5Zy5Q.png" /></figure><p>Here are the topics on the <strong>async </strong>coroutine builder</p><blockquote><strong><em>What are the coroutine builders in Kotlin?</em></strong></blockquote><blockquote><strong><em>Key Characteristics of the </em></strong><strong>async <em>Builder</em></strong></blockquote><blockquote><strong><em>How the </em></strong><strong>async<em>Coroutine Builder Works Under the Hood</em></strong></blockquote><blockquote><strong><em>What role does the </em></strong><em>Job </em><strong><em>play in helping a Deferred object know when its associated task is completed?</em></strong></blockquote><blockquote><strong><em>What happens when a cancellable suspending function is waiting and the associated </em></strong><strong><em>Job of the current coroutine is cancelled or completed?</em></strong></blockquote><blockquote><strong><em>How Exceptions Work in </em></strong><strong><em>async:</em></strong></blockquote><p>Coroutine builders are functions which is used to create a coroutine. It can be called from normal functions because they do not suspend themselves. They act as a link between the suspending and non-suspending parts of our code.</p><p><strong>What are the coroutine builders in Kotlin?</strong></p><p>In Kotlin, <strong>coroutine builders</strong> are functions that allow you to create and start coroutines. The main coroutine builders are</p><p><strong>launch</strong>:</p><ul><li>Starts a new coroutine and doesn’t return any result.</li><li>Often used for fire-and-forget tasks, where you don’t need a result.</li></ul><pre>GlobalScope.launch {<br>    // Background task<br>}</pre><p><strong>async</strong>:</p><ul><li>Starts a new coroutine and returns a <strong>Deferred</strong> object, which allows you to retrieve a result later.</li><li>Useful for parallel computations when you need a result.</li></ul><pre>val result = GlobalScope.async {<br>    // Some computation<br>    42<br>}<br>println(result.await()) // Waits for the result</pre><p><strong>withContext</strong>:</p><ul><li>Changes the context of an already running coroutine (e.g., switching to Dispatchers.IO for I/O operations).</li><li>Does not start a new coroutine but modifies the execution context.</li></ul><pre>GlobalScope.launch {<br>    val data = withContext(Dispatchers.IO) {<br>        // Perform I/O operations<br>        &quot;Fetched data&quot;<br>    }<br>    println(data)<br>}</pre><p><strong>runBlocking</strong>:</p><ul><li>Starts a coroutine that blocks the current thread until it completes. Used in main functions or tests to bridge regular code with coroutines.</li></ul><pre>runBlocking {<br>    // Coroutine inside a blocking call<br>    delay(1000)<br>    println(&quot;Done&quot;)<br>}</pre><p>These builders help manage how coroutines are launched and controlled within different contexts and scopes.</p><p><strong>The </strong><strong>async coroutine builder:</strong></p><p>The async coroutine builder in Kotlin is used to launch a new coroutine that runs concurrently and returns a <strong>Deferred</strong> result, which represents a promise of a future value. It is specifically designed for performing asynchronous operations in parallel. Unlike the launch builder, which returns Job and doesn&#39;t carry any result, async provides the ability to return a value once the computation is completed.</p><p><strong>Key characteristics of the </strong><strong>async:</strong></p><ul><li><strong>Concurrent Execution</strong>: The async builder allows the coroutine to execute concurrently with other coroutines or tasks. It does not block the main thread and enables parallel execution when needed, especially useful in CPU-bound or I/O-bound tasks.</li><li><strong>Deferred Result</strong>: Unlike launch, which returns a Job, async returns a Deferred&lt;T&gt;. This Deferred is a lightweight, non-blocking future result that can be awaited using await(), meaning the calling coroutine will suspend until the result is ready.</li><li><strong>Lazy or Eager Execution</strong>: By default, async starts executing eagerly when it&#39;s called. However, it can be made lazy by passing start = CoroutineStart.LAZY, which delays execution until await() or start() is explicitly called.</li><li><strong>Structured Concurrency</strong>: async is often used within structured concurrency, ensuring that the parent coroutine waits for its child async coroutines to complete, preventing memory leaks or unintended behavior.</li></ul><p><strong>How </strong>async <strong>Coroutine builder works under the hood ?</strong></p><p>Function Signature:</p><pre>public fun &lt;T&gt; CoroutineScope.async(<br>    context: CoroutineContext = EmptyCoroutineContext,<br>    start: CoroutineStart = CoroutineStart.DEFAULT,<br>    block: suspend CoroutineScope.() -&gt; T<br>): Deferred&lt;T&gt; {<br>    val newContext = newCoroutineContext(context)<br>    val coroutine = if (start.isLazy)<br>        LazyDeferredCoroutine(newContext, block) else<br>        DeferredCoroutine&lt;T&gt;(newContext, active = true)<br>    coroutine.start(start, coroutine, block)<br>    return coroutine<br>}</pre><p><strong>CoroutineScope.async(...)</strong>:</p><ul><li>The async function is an <strong>extension function</strong> on CoroutineScope. This means that you must call async inside a CoroutineScope. It inherits the context of that scope unless overridden.</li></ul><p><strong>context: CoroutineContext = EmptyCoroutineContext</strong>:</p><ul><li>The context parameter is optional, with a default value of EmptyCoroutineContext. This allows you to specify a custom CoroutineContext, such as Dispatchers.IO or a custom Job. If you don&#39;t pass a context, the default EmptyCoroutineContext will be used, inheriting the context of the parent scope.</li><li><strong>start: CoroutineStart = CoroutineStart.DEFAULT</strong>:</li><li>start controls when the coroutine starts. By default, it uses CoroutineStart.DEFAULT, which means the coroutine starts immediately. You can pass other values like CoroutineStart.LAZY, which defers the coroutine&#39;s start until explicitly triggered by calling start() or await().</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val deferred = async(start = CoroutineStart.LAZY) {<br>        println(&quot;Coroutine started lazily!&quot;)<br>        &quot;Result&quot;<br>    }<br>    println(&quot;Doing other work...&quot;)<br>    deferred.start()  // Explicitly start the coroutine<br>    val result = deferred.await()  // Now we can get the result<br>    println(&quot;Deferred result: $result&quot;)<br>}<br><br>// Output of the program <br>Doing other work...<br>Coroutine started lazily!<br>Deferred result: Result</pre><p><strong>block: suspend CoroutineScope.() -&gt; T</strong>:</p><ul><li>This is the <strong>suspending lambda</strong> that contains the code to be run asynchronously. The block is executed in the context of the coroutine and can call suspending functions. It’s an extension on CoroutineScope, so you have access to the scope’s properties within the block.</li></ul><p><strong>: Deferred&lt;T&gt;</strong>:</p><ul><li>The function returns a Deferred&lt;T&gt;, which represents a future value of type T. The Deferred interface extends Job and allows you to await() the result, making this coroutine capable of returning a result after the asynchronous task completes.</li></ul><pre>val newContext = newCoroutineContext(context)</pre><p><strong>newCoroutineContext(context)</strong>:</p><ul><li>This creates a new coroutine context by merging the provided context with the CoroutineScope&#39;s context. If you didn&#39;t pass a context, it uses the EmptyCoroutineContext and merges it with the scope&#39;s context. This ensures that the coroutine has all the required properties (like dispatcher, job, etc.) for its execution.</li></ul><pre>val coroutine = if (start.isLazy)<br>    LazyDeferredCoroutine(newContext, block) else<br>    DeferredCoroutine&lt;T&gt;(newContext, active = true)</pre><p><strong>if (start.isLazy)</strong>:</p><ul><li>This checks whether the start mode is lazy, i.e., CoroutineStart.LAZY. If the isLazy flag is true, the coroutine won&#39;t start immediately but will wait for an explicit trigger (like await() or calling start()).</li></ul><p><strong>LazyDeferredCoroutine(newContext, block)</strong>:</p><ul><li>If start is lazy, it creates a LazyDeferredCoroutine, which is a specific type of coroutine that doesn&#39;t start running until it&#39;s explicitly started. It takes the new context (newContext) and the block of code to execute (block).</li></ul><p><strong>DeferredCoroutine&lt;T&gt;(newContext, active = true)</strong>:</p><ul><li>If the coroutine is not lazy (the default behavior), it creates a DeferredCoroutine&lt;T&gt;. This is an active coroutine that immediately starts executing after creation. It takes newContext to determine its context and active = true indicates that the coroutine is immediately ready to run.</li></ul><pre>coroutine.start(start, coroutine, block)</pre><p><strong>coroutine.start(start, coroutine, block)</strong>:</p><ul><li>This starts the coroutine based on the start parameter. The start function schedules the coroutine for execution. If start is DEFAULT, the coroutine starts immediately. If it&#39;s LAZY, the coroutine will wait for explicit starting.</li><li>The start() method takes:</li><li>start: The CoroutineStart mode (e.g., DEFAULT, LAZY).</li><li>coroutine: The coroutine instance itself.</li><li>block: The block of code to be executed.</li></ul><pre>return coroutine</pre><p><strong>return coroutine</strong>:</p><ul><li>Finally, the function returns the coroutine, which is a Deferred&lt;T&gt; object. This object represents the result of the coroutine. You can use the Deferred to either:</li><li>await() the result when it&#39;s ready (suspending the caller until the result is available).</li><li>Check if the coroutine is completed, cancelled, or active.</li></ul><p><strong>What role does the </strong>Job <strong>play in helping a Deferred object know when its associated task is completed?</strong></p><p>The Job plays a critical role in managing the lifecycle of a coroutine and its associated Deferred object in Kotlin.</p><ul><li><strong>Lifecycle Management</strong>: The Job is responsible for tracking the state of a coroutine. It maintains information about whether the coroutine is active, completed, or canceled. The Deferred object inherits this functionality, allowing it to access the current state of the associated Job.</li><li><strong>Completion Status</strong>: When you call await() on a Deferred, it internally checks the state of its Job. If the Job indicates that the coroutine has completed (successfully or with an exception), await() can return the result immediately. If the Job shows that the coroutine is still running, await() suspends the coroutine until it finishes.</li><li><strong>State Transition Notifications</strong>: The Job emits state change events during the coroutine’s lifecycle. When the coroutine completes, the Job transitions to a completed state, which triggers any suspended await() calls to resume. This notification mechanism allows Deferred to know that it can safely provide the result.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val deferred: Deferred&lt;String&gt; = async {<br>        delay(1000) // Simulate work<br>        &quot;Result&quot;<br>    }<br><br>    // The Job associated with Deferred is checked here<br>    if (deferred.isCompleted) {<br>        println(deferred.await()) // Not yet completed<br>    } else {<br>        println(&quot;Awaiting result...&quot;)<br>        val result = deferred.await() // This will suspend until completion<br>        println(result) // Prints: Result<br>    }<br>}</pre><ul><li><strong>State Tracking</strong>: Job tracks whether the coroutine is running or has completed.</li><li><strong>Await Functionality</strong>: The await() function relies on the Job to determine if it can return a result or needs to suspend.</li><li><strong>Notifications</strong>: Job handles notifications about state changes, allowing Deferred to react appropriately when the coroutine completes.</li></ul><p><strong>What happens when a cancellable suspending function is waiting and the associated </strong><strong>Job of the current coroutine is cancelled or completed?</strong></p><ul><li><strong>Immediate Resumption with Cancellation</strong>: If the Job is cancelled while the suspending function is waiting, the function will immediately resume with a CancellationException. This means that the function will not complete successfully and will throw this exception to signal that the coroutine was cancelled.</li><li><strong>No Successful Resumption</strong>: The suspending function will not continue execution or return a result if the coroutine’s Job was cancelled during its suspension. Instead, the coroutine that called the suspending function will be terminated.</li><li><strong>Prompt Cancellation Guarantee</strong>: This behavior ensures that the cancellation is handled promptly, allowing the coroutine to react to the cancellation in a timely manner, preventing it from continuing to execute any further logic or computations that may no longer be relevant.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val job = launch {<br>        // This is a cancellable suspending function<br>        suspendCancellableCoroutine&lt;String&gt; { continuation -&gt;<br>            // Simulate some work<br>            try {<br>                delay(5000)<br>                continuation.resume(&quot;Result&quot;)<br>            } catch (e: CancellationException) {<br>                continuation.resumeWithException(e) // Handle cancellation<br>            }<br>        }<br>    }<br><br>    delay(1000) // Wait for a bit before cancelling<br>    job.cancel() // Cancel the Job<br><br>    try {<br>        job.join() // Wait for the job to finish<br>    } catch (e: CancellationException) {<br>        println(&quot;Job was cancelled&quot;) // This will execute<br>    }<br>}</pre><ul><li>The coroutine initiates a cancellable suspending function.</li><li>If the Job is cancelled before the function completes, it will not resume successfully; instead, it will throw a CancellationException.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*jqz_OgIFKs06X2miY4gEaA.png" /></figure><h4><strong>How Exceptions Work in </strong><strong>async:</strong></h4><p><strong>Exception Propagation</strong>:</p><ul><li>If an exception occurs within the coroutine launched by async, it does not propagate immediately. Instead, the exception is captured and stored in the Deferred object. The Deferred will represent a failed computation when await() is called.</li></ul><p><strong>Awaiting the Result</strong>:</p><ul><li>When you call await() on a Deferred, it checks if the coroutine completed successfully or with an exception:</li><li><strong>Successful Completion</strong>: If the coroutine completed successfully, await() returns the result.</li><li><strong>Exception Occurred</strong>: If the coroutine encountered an exception, await() throws that exception (the original exception thrown within the coroutine).</li></ul><p><strong>Structured Concurrency</strong>:</p><ul><li>If a parent coroutine is cancelled, all its child coroutines (including those started with async) will be cancelled as well. If an exception occurs in one of the child coroutines, the parent can handle it appropriately, ensuring structured concurrency.</li></ul><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    val deferred: Deferred&lt;String&gt; = async {<br>        // Simulating some work<br>        delay(1000)<br>        if (true) { // Simulating an error condition<br>            throw IllegalArgumentException(&quot;Something went wrong&quot;)<br>        }<br>        &quot;Success&quot;<br>    }<br><br>    try {<br>        val result = deferred.await() // This will throw an exception<br>        println(result)<br>    } catch (e: Exception) {<br>        println(&quot;Caught exception: ${e.message}&quot;) // Handle the exception<br>    }<br>}</pre><ul><li><strong>Deferred Object</strong>: The Deferred object captures exceptions, allowing you to handle them later when calling await().</li><li><strong>Await Behavior</strong>: await() throws the original exception if the coroutine fails, allowing you to catch and handle it.</li><li><strong>Structured Concurrency</strong>: Parent coroutines can manage exceptions from child coroutines, ensuring that exceptions do not go unhandled.</li></ul><p>Here are some important and advanced questions regarding the async coroutine builder in Kotlin, along with brief explanations for each:</p><p><strong>1. What is the purpose of the </strong><strong>async coroutine builder, and how does it differ from </strong><strong>launch?</strong></p><ul><li>The async coroutine builder is used when you want to execute a coroutine concurrently and <strong>return a result</strong>. It returns a Deferred&lt;T&gt;, which represents a future result that can be awaited.</li><li>The primary difference between async and launch is that async is used for <strong>returning a value</strong> with await(), while launch is used for <strong>fire-and-forget</strong> operations without any returned result.</li></ul><p><strong>2. What is </strong><strong>Deferred, and how does it relate to </strong><strong>async?</strong></p><p>Deferred&lt;T&gt; is the result type returned by async. It is similar to Job, but it also allows you to <strong>retrieve a result</strong> once the coroutine finishes. You can call the await() function on a Deferred to get the result once it is available.</p><p><strong>3. How does the </strong><strong>await() function work, and is it blocking?</strong></p><p>await() is a <strong>suspending function</strong>, which means it will suspend the coroutine where it is called until the result of the async coroutine is available. It is <strong>non-blocking</strong>, meaning it doesn&#39;t block the current thread, but allows other coroutines to run while waiting for the result.</p><p><strong>4. What happens if an exception occurs in a coroutine started with </strong><strong>async?</strong></p><p>If an exception occurs inside a coroutine created with async, it will be <strong>propagated</strong> when you call await(). The Deferred will fail, and trying to get the result will throw the exception. You can handle this with try-catch around await() or within the coroutine itself.</p><p><strong>5. How can you combine the results of multiple </strong><strong>async coroutines?</strong></p><p>You can use await() on multiple Deferred objects to combine results from multiple async coroutines. This can be done using awaitAll() or awaiting each result individually.</p><pre>val result1 = async { doWork1() }<br>val result2 = async { doWork2() }<br><br>val combinedResult = result1.await() + result2.await()</pre><p><strong>6. How does </strong><strong>async(start = CoroutineStart.LAZY) work, and when should you use it?</strong></p><p>Using CoroutineStart.LAZY with async means that the coroutine won’t start executing until its result is awaited by calling await(). This is useful when you want to <strong>defer the coroutine execution</strong> until the result is actually needed.</p><pre>val deferred = async(start = CoroutineStart.LAZY) { doExpensiveWork() }<br>deferred.start() // Manually start the coroutine<br>val result = deferred.await() // Or await which also starts the coroutine</pre><p><strong>7. Can </strong><strong>async coroutines be cancelled, and how does cancellation work with </strong><strong>await()?</strong></p><p>Yes, async coroutines can be cancelled like any other coroutine. If the parent coroutine or job is cancelled, the async coroutine will also be cancelled. If you call await() on a cancelled Deferred, it will throw a CancellationException.</p><p><strong>8. What is the behavior of </strong><strong>await() when called multiple times on the same </strong><strong>Deferred?</strong></p><p>If you call await() multiple times on the same Deferred, it will <strong>return the same result</strong> if the coroutine has completed. Deferred caches the result once the coroutine finishes, so subsequent calls to await() will return the cached value.</p><p><strong>9. How does structured concurrency apply to </strong><strong>async coroutines?</strong></p><p>Structured concurrency means that <strong>all child coroutines</strong> (including async) are <strong>bound to the lifecycle</strong> of the parent coroutine scope. If the parent scope is cancelled, all async coroutines within that scope will also be cancelled. This ensures that you do not have dangling or orphaned coroutines running</p><p><strong>10. How does </strong><strong>async handle context switching and dispatchers?</strong></p><p>Like other coroutines, async respects the coroutine <strong>context and dispatcher</strong>. You can specify a dispatcher (e.g., Dispatchers.IO, Dispatchers.Default) to run async coroutines on a specific thread pool. The coroutine execution will happen on the provided dispatcher, and the await() function will resume on the original thread where it was suspended, unless a different context is used.</p><p><strong>11. How does exception handling with </strong><strong>async differ from </strong><strong>launch?</strong></p><p>With launch, exceptions are propagated to the parent coroutine automatically. With async, exceptions are stored and will only be propagated when await() is called. This means you may not see an exception immediately in an async coroutine until you attempt to retrieve the result using await().</p><p><strong>12. Can you use </strong><strong>async without </strong><strong>await()? What happens in this case?</strong></p><p>Yes, you can use async without calling await(), but this will result in <strong>ignoring the result</strong> of the coroutine. In this case, the coroutine will still execute in the background, but its result will not be used. If an exception occurs, it will be ignored unless you handle it explicitly by calling await().</p><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a32b6dda3bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: ‘launch’ coroutine builder]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-coroutines-launch-coroutine-builder-a2abcd87d7a6?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2abcd87d7a6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[launch]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 04:47:36 GMT</pubDate>
            <atom:updated>2024-10-09T05:18:54.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGx2zTmLQDmr7bfDoCxcog.png" /></figure><p>Here are the topics on the launch coroutine builder</p><blockquote><strong><em>Why do we have to use coroutine builders in Kotlin?</em></strong></blockquote><blockquote><strong><em>Key Characteristics of the </em></strong><strong><em>launch Builder</em></strong></blockquote><blockquote><strong><em>How the </em></strong><strong><em>launch Coroutine Builder Works Under the Hood</em></strong></blockquote><blockquote><strong><em>How the </em></strong><strong><em>Job Returned by the </em></strong><strong><em>launch Coroutine Builder Helps as a Reference, and What It Does</em></strong></blockquote><blockquote><strong><em>When an exception occurs in a coroutine launched using the </em></strong><strong><em>launch builder, How does it handle?</em></strong></blockquote><p>Coroutine builders are functions which is used to create a coroutine. It can be called from normal functions because they do not suspend themselves. They act as a link between the suspending and non-suspending parts of our code.</p><h4><strong>What are the coroutine builders in Kotlin?</strong></h4><p>In Kotlin, <strong>coroutine builders</strong> are functions that allow you to create and start coroutines. The main coroutine builders are</p><p><strong>launch</strong>:</p><ul><li>Starts a new coroutine and doesn’t return any result.</li><li>Often used for fire-and-forget tasks, where you don’t need a result.</li></ul><pre>GlobalScope.launch {<br>    // Background task<br>}</pre><p><strong>async</strong>:</p><ul><li>Starts a new coroutine and returns a <strong>Deferred</strong> object, which allows you to retrieve a result later.</li><li>Useful for parallel computations when you need a result.</li></ul><pre>val result = GlobalScope.async {<br>    // Some computation<br>    42<br>}<br>println(result.await()) // Waits for the result</pre><p><strong>withContext</strong>:</p><ul><li>Changes the context of an already running coroutine (e.g., switching to Dispatchers.IO for I/O operations).</li><li>Does not start a new coroutine but modifies the execution context.</li></ul><pre>GlobalScope.launch {<br>    val data = withContext(Dispatchers.IO) {<br>        // Perform I/O operations<br>        &quot;Fetched data&quot;<br>    }<br>    println(data)<br>}</pre><p><strong>runBlocking</strong>:</p><ul><li>Starts a coroutine that blocks the current thread until it completes. Used in main functions or tests to bridge regular code with coroutines.</li></ul><pre>runBlocking {<br>    // Coroutine inside a blocking call<br>    delay(1000)<br>    println(&quot;Done&quot;)<br>}</pre><p>These builders help manage how coroutines are launched and controlled within different contexts and scopes.</p><p><strong>Why do we have to use coroutine builders in Kotlin?</strong></p><p>We <strong>have to use coroutine builders</strong> in Kotlin because they provide the only way to <strong>create and control the execution</strong> of coroutines. Without these builders (launch, async, withContext), there is no mechanism to initiate, manage, or handle coroutines. They are essential for</p><ol><li><strong>Starting coroutines</strong> to perform background or asynchronous tasks.</li><li><strong>Controlling execution contexts</strong>, ensuring the right dispatcher (thread) is used.</li><li><strong>Managing concurrency</strong> by structuring how coroutines run and interact with each other.</li></ol><p>Without builders, Kotlin coroutines cannot function properly.</p><p><strong>The </strong><strong>launch coroutine builder:</strong></p><p>The launch coroutine builder is one of the most commonly used tools for launching coroutines in Kotlin. It is specifically designed for <strong>fire-and-forget</strong> tasks where you do not need a result and are mainly concerned with running background operations asynchronously.</p><p><strong>Key Characteristics:</strong></p><ol><li><strong>Non-blocking Execution</strong>:</li></ol><ul><li>The launch function <strong>does not block</strong> the current thread. It immediately schedules the coroutine for execution in the provided context and returns a <strong>Job</strong> reference, which represents the running coroutine.</li><li><strong>Job</strong> is an interface that allows you to control and manage the coroutine&#39;s lifecycle (such as cancellation, checking completion, etc.).</li></ul><p><strong>2. Job Cancellation</strong>:</p><ul><li>If the resulting <strong>Job</strong> is cancelled, the coroutine is also cancelled. This creates a hierarchical cancellation system, where a parent job can cancel child coroutines.</li><li>You can manually cancel the <strong>Job</strong> by calling job.cancel().</li></ul><p><strong>3. Coroutine Context</strong>:</p><ul><li>The coroutine <strong>inherits the context</strong> of the <strong>CoroutineScope</strong> in which it was launched.</li><li>Additional context elements can be specified using the context parameter in the launch function, allowing you to override or extend the default coroutine context.</li></ul><pre>launch(Dispatchers.IO + CoroutineName(&quot;WorkerJob&quot;)) { <br>    // Coroutine code<br>}</pre><ul><li>If no <strong>dispatcher</strong> or <strong>ContinuationInterceptor</strong> is provided, the coroutine defaults to <strong>Dispatchers.Default</strong>.</li></ul><p>4. <strong>Start Parameter</strong>:</p><p>By default, the coroutine is immediately <strong>scheduled for execution</strong>. However, you can control its start behavior by specifying the <strong>start</strong> parameter:</p><ul><li><strong>CoroutineStart.DEFAULT</strong>: Coroutine starts immediately.</li><li><strong>CoroutineStart.LAZY</strong>: The coroutine is not started immediately and will only start when <strong>start()</strong> or <strong>join()</strong> is called. This is useful when you want to delay the execution until necessary.</li><li>Example using CoroutineStart.LAZY</li></ul><pre>val job = launch(start = CoroutineStart.LAZY) {<br>    println(&quot;This runs lazily&quot;)<br>}<br>job.start()  // Explicitly start the coroutine</pre><p><strong>5. Exception Handling</strong>:</p><ul><li>By default, any uncaught exception in the coroutine will <strong>cancel</strong> the parent job (if it exists). This is important for ensuring that failure in a child coroutine can propagate to the parent coroutine and clean up resources.</li><li>You can customize exception handling using <strong>CoroutineExceptionHandler</strong> to prevent the cancellation of the parent job.</li></ul><pre>val handler = CoroutineExceptionHandler { _, exception -&gt;<br>    println(&quot;Caught exception: $exception&quot;)<br>}<br>val job = launch(Dispatchers.Default + handler) {<br>    throw RuntimeException(&quot;Test Exception&quot;)<br>}</pre><p><strong>6. Parameters</strong>:</p><ul><li><strong>context</strong>: An optional parameter to provide additional context (like dispatcher, exception handler, etc.) for the coroutine.</li><li><strong>start</strong>: Specifies when the coroutine should start. The default is <strong>CoroutineStart.DEFAULT</strong> (immediate start). It can also be set to <strong>CoroutineStart.LAZY</strong>.</li><li><strong>block</strong>: The <strong>coroutine code block</strong> that will execute within the coroutine scope.</li></ul><p><strong>Let’s consider a situation where we need to handle multiple background tasks (e.g., downloading files) concurrently, while allowing the main thread to continue with UI updates or other work:</strong></p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    println(&quot;Main thread starts.&quot;)<br><br>    // Launching multiple background tasks<br>    val job1 = launch(Dispatchers.IO) {<br>        delay(2000)  // Simulate file download<br>        println(&quot;File 1 downloaded!&quot;)<br>    }<br><br>    val job2 = launch(Dispatchers.IO) {<br>        delay(1000)  // Simulate faster download<br>        println(&quot;File 2 downloaded!&quot;)<br>    }<br><br>    println(&quot;Main thread is free to do other work.&quot;)<br>    <br>    // Wait for both background tasks to finish<br>    job1.join()<br>    job2.join()<br><br>    println(&quot;Main thread ends.&quot;)<br>}<br><br>// Output of the program<br>Main thread starts.<br>Main thread is free to do other work.<br>File 2 downloaded!<br>File 1 downloaded!<br>Main thread ends.</pre><ul><li><strong>Launching Coroutines</strong>: Two coroutines are launched in the background using launch, one for downloading file 1 and another for file 2. Both tasks run in parallel and don’t block the main thread.</li><li><strong>Main Thread Continuation</strong>: The main thread continues executing and prints &quot;Main thread is free to do other work.&quot; while the background tasks are running concurrently.</li><li><strong>Coroutine Completion</strong>: The join() function is used to wait for the background tasks to complete before the main thread ends.</li></ul><h4>How launch Coroutine builder works under the hood ?</h4><p>Function Signature:</p><pre>public fun CoroutineScope.launch(<br>    context: CoroutineContext = EmptyCoroutineContext,<br>    start: CoroutineStart = CoroutineStart.DEFAULT,<br>    block: suspend CoroutineScope.() -&gt; Unit<br>): Job {<br>    val newContext = newCoroutineContext(context)<br>    val coroutine = if (start.isLazy)<br>        LazyStandaloneCoroutine(newContext, block) else<br>        StandaloneCoroutine(newContext, active = true)<br>    coroutine.start(start, coroutine, block)<br>    return coroutine<br>}{</pre><ul><li><strong>CoroutineScope.launch</strong>: A member function of CoroutineScope that creates and launches a new coroutine.</li><li><strong>context: CoroutineContext</strong>: The context defines the environment in which the coroutine will run. By default, it is EmptyCoroutineContext, meaning the coroutine will use the scope&#39;s existing context unless additional context elements (like Dispatchers.IO) are provided.</li><li><strong>start: CoroutineStart</strong>: Defines when the coroutine starts. The default is CoroutineStart.DEFAULT, which starts the coroutine immediately, but it can be LAZY (start only when needed).</li><li><strong>block: suspend CoroutineScope.() -&gt; Unit</strong>: The coroutine block containing the logic to execute. It is a suspending function that receives the coroutine scope as its receiver.</li></ul><p><strong>The </strong><strong>newCoroutineContext Call:</strong></p><pre>val newContext = newCoroutineContext(context)</pre><ul><li><strong>newCoroutineContext(context)</strong>: This function combines the current coroutine scope’s context with the provided context. If the context is empty (EmptyCoroutineContext), the coroutine will inherit the scope’s existing context. Otherwise, the provided context will override or add to the scope’s context. For example, if Dispatchers.IO is passed, the coroutine will run in the I/O dispatcher.</li><li>This step ensures that the new coroutine has the correct execution environment (dispatcher, job, etc.).</li></ul><pre>val scope = CoroutineScope(Job()) // No dispatcher specified<br><br>scope.launch {<br>    // Uses the default context, which is typically Dispatchers.Default<br>    println(&quot;Running on ${Thread.currentThread().name}&quot;)<br>}</pre><p>In this example:</p><ul><li>Since no dispatcher is provided, Dispatchers.Default is used as the default context for the coroutine.</li></ul><pre>scope.launch(Dispatchers.IO) {<br>    // Now using Dispatchers.IO, overriding any default<br>    println(&quot;Running on ${Thread.currentThread().name}&quot;)<br>}</pre><p><strong>Creating the Coroutine Object:</strong></p><pre>val coroutine = if (start.isLazy)<br>    LazyStandaloneCoroutine(newContext, block)<br>else<br>    StandaloneCoroutine(newContext, active = true)</pre><p><strong>coroutine</strong>: This defines the type of coroutine to be created based on the start parameter.</p><ul><li>If start.isLazy is true, a <strong>LazyStandaloneCoroutine</strong> is created. This coroutine is not started immediately. It will only start when the result is requested (if it&#39;s a Deferred) or manually triggered with .start().</li><li>Otherwise, a <strong>StandaloneCoroutine</strong> is created and is immediately active (active = true). This means the coroutine will start execution right away.</li></ul><p>Both LazyStandaloneCoroutine and StandaloneCoroutine are implementations of coroutines that manage their lifecycle and behavior.</p><p><strong>Starting the Coroutine:</strong></p><pre>coroutine.start(start, coroutine, block)</pre><p><strong>coroutine.start(start, coroutine, block)</strong>: This method is called to begin the execution of the coroutine. Depending on the value of start:</p><ul><li>If start is CoroutineStart.DEFAULT, the coroutine starts executing immediately.</li><li>If start is CoroutineStart.LAZY, it will remain inactive until triggered.</li></ul><p>The block (the actual coroutine code) is passed here for execution when the coroutine starts.</p><p><strong>Returning the Job:</strong></p><pre>return coroutine</pre><p>The launch function returns a <strong>Job</strong> object, which represents the coroutine. This Job can be used to track the coroutine&#39;s lifecycle (whether it’s active, completed, or canceled) and cancel it if needed.</p><p><strong>How does the </strong><strong>Job returned by the </strong><strong>launch coroutine builder help as a reference, and what does it do?</strong></p><p>The <strong>Job</strong> returned by the <strong>launch</strong> coroutine builder serves as a reference for managing and controlling the coroutine&#39;s lifecycle.</p><p><strong>1. Managing the Coroutine’s Lifecycle</strong></p><ul><li><strong>Job allows you to track and control the coroutine&#39;s lifecycle</strong>, including whether it&#39;s running, completed, or canceled.</li><li>The launch coroutine builder does not return a result (unlike async), but it returns a Job that can be used to interact with the coroutine while it is running.</li></ul><h4>What Does Job Do?</h4><p><strong>1. Cancellation</strong></p><ul><li>One of the key features of the Job is that it allows you to <strong>cancel</strong> a coroutine before it completes.</li><li>You might need to cancel a coroutine due to changes in the application’s state, user interactions, or system events. For example, you may want to cancel ongoing network requests or computations when a user navigates away from a screen.</li></ul><pre>val job = CoroutineScope(Dispatchers.IO).launch {<br>    // Simulate long-running task<br>    repeat(100) {<br>        delay(100)<br>        println(&quot;Running task $it&quot;)<br>    }<br>}<br><br>// Cancel the job after 500ms<br>delay(500)<br>job.cancel() // Cancels the coroutine</pre><p><strong>What happens</strong>: After calling job.cancel(), the coroutine is stopped, and any further code in the coroutine will not be executed. This is useful for stopping unnecessary or long-running tasks.</p><p><strong>2. Monitoring State:</strong></p><ul><li>The Job reference provides information about the current state of the coroutine. You can <strong>monitor whether the coroutine is active, completed, or canceled</strong>.</li></ul><p><strong>Useful properties</strong>:</p><ul><li><strong>job.isActive</strong>: Returns true if the coroutine is currently running.</li><li><strong>job.isCompleted</strong>: Returns true if the coroutine has finished execution (either completed or canceled).</li><li><strong>job.isCancelled</strong>: Returns true if the coroutine has been canceled.</li></ul><pre>val job = CoroutineScope(Dispatchers.IO).launch {<br>    delay(1000)<br>    println(&quot;Coroutine is complete&quot;)<br>}<br><br>println(&quot;Job is active: ${job.isActive}&quot;)   // true<br>delay(1500)                                 // Wait for coroutine to finish<br>println(&quot;Job is completed: ${job.isCompleted}&quot;)  // true after completion</pre><p><strong>What happens</strong>: You can check the state of the coroutine during and after its execution using the Job reference. This helps in scenarios where you need to synchronize with other tasks or manage state transitions.</p><p><strong>3. Waiting for Coroutine Completion:</strong></p><ul><li>You can use the Job to <strong>wait for the coroutine to complete</strong> using job.join(). This suspends the current coroutine or function until the coroutine finishes, allowing you to coordinate when certain tasks should proceed.</li></ul><pre>val job = CoroutineScope(Dispatchers.Default).launch {<br>    delay(2000)<br>    println(&quot;Task finished&quot;)<br>}<br><br>println(&quot;Waiting for coroutine to complete...&quot;)<br>job.join()  // Suspends until the coroutine finishes<br>println(&quot;Coroutine has finished&quot;)</pre><p><strong>What happens</strong>: job.join() ensures that the code after the join does not execute until the coroutine completes. This is useful in cases where you need to wait for a background task to complete before proceeding.</p><p><strong>4. Parent-Child Coroutine Relationships:</strong></p><ul><li><strong>Job hierarchy</strong>: If you launch coroutines within another coroutine, the parent coroutine’s Job automatically manages the child coroutines. If the parent coroutine&#39;s Job is canceled, all child coroutines are also canceled.</li></ul><pre>val parentJob = CoroutineScope(Dispatchers.Default).launch {<br>    val childJob = launch {<br>        delay(2000)<br>        println(&quot;Child coroutine completed&quot;)<br>    }<br>    println(&quot;Parent coroutine waiting for child&quot;)<br>    childJob.join()<br>    println(&quot;Parent coroutine completed&quot;)<br>}<br><br>// Cancel the parent coroutine, this will also cancel the child<br>parentJob.cancel()</pre><p><strong>What happens</strong>: When you cancel parentJob, both the parent and child coroutines will be canceled, ensuring structured concurrency.</p><p><strong>When an exception occurs in a coroutine launched using the </strong><strong>launch builder, How does it handle?</strong></p><p><strong>1. Immediate Exception Propagation:</strong></p><ul><li>When a coroutine created by launch throws an exception, it propagates the exception to the parent coroutine immediately.</li><li>If there is no parent (i.e., in a GlobalScope coroutine), the exception is uncaught and will terminate the coroutine. By default, this will log the exception and cancel the rest of the job hierarchy, but the coroutine doesn&#39;t fail silently.</li></ul><p><strong>2. CoroutineExceptionHandler:</strong></p><ul><li>You can handle exceptions in a launch coroutine by using CoroutineExceptionHandler. This handler intercepts any uncaught exceptions.</li></ul><pre>val handler = CoroutineExceptionHandler { _, exception -&gt;<br>    println(&quot;Caught $exception&quot;)<br>}<br><br>GlobalScope.launch(handler) {<br>    throw Exception(&quot;Error in launch&quot;)<br>}</pre><p>If the exception occurs in a child coroutine, it propagates up to the parent until it is handled, or reaches the root and is logged.</p><p><strong>3. Job Cancellation</strong></p><ul><li>Any exception inside a launch coroutine results in its cancellation. If a coroutine has child coroutines, the exception causes the entire hierarchy of coroutines to be cancelled.</li><li>You can check the status of a Job to see if the coroutine was cancelled due to an exception using isCancelled or join().</li></ul><p><strong>4. Uncaught Exceptions in Structured Concurrency</strong></p><ul><li>If you are using structured concurrency (e.g., launching coroutines within a CoroutineScope), unhandled exceptions are automatically propagated to the scope&#39;s parent.</li><li>For instance, in a Supervisor Job, exceptions in child coroutines won&#39;t cancel other sibling coroutines unless explicitly handled.</li></ul><pre>val supervisor = SupervisorJob()<br>val scope = CoroutineScope(Dispatchers.Default + supervisor)<br><br>scope.launch {<br>    throw Exception(&quot;Error in child coroutine&quot;) // Won&#39;t affect other coroutines<br>}</pre><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2abcd87d7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines: Suspend Function]]></title>
            <link>https://medium.com/@guruprasadhegde4/kotlin-coroutines-suspend-function-f98ebbbd3bd7?source=rss-3d3f7ac863cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f98ebbbd3bd7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[suspend-function]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Guruprasad Hegde]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 05:18:13 GMT</pubDate>
            <atom:updated>2024-10-08T05:18:13.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines: Suspend Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-b5zybZAAACLnewVjl5Xw.png" /></figure><h4>What is suspend function?</h4><p>In Kotlin, a suspend function is a special type of function designed for asynchronous programming. function can be paused and resumed later, without blocking the thread it’s running on. This is a key feature that enables coroutines to perform asynchronous operations efficiently.</p><ul><li><strong>Non-blocking Pauses</strong>: A suspend function can pause its execution without blocking the current thread. It allows other tasks to run while waiting for a long-running operation to complete (like a network request or file I/O).</li><li><strong>Used with Coroutines</strong>: It can only be called from another suspend function or within a coroutine. Coroutines provide a structured way to manage asynchronous tasks.</li><li><strong>Looks Synchronous</strong>: Although asynchronous, suspend functions look and behave like regular functions, making code easier to write and read without callbacks.</li></ul><blockquote>When you add the suspend keyword to a function, you’re telling the compiler that this function can be suspended.</blockquote><blockquote>Suspending a function means that its execution is temporarily paused, and the current thread can move on to execute other tasks.</blockquote><blockquote>Later, the suspended function can be resumed from where it left off, continuing its execution.</blockquote><h4><strong>Syntax of suspend function:</strong></h4><pre>suspend fun functionName(parameters): ReturnType {<br>    // Function body<br>}</pre><pre>suspend fun fetchData(url: String): String {<br>    // Simulate a long-running operation (like network request)<br>    delay(1000)  // Suspends the coroutine without blocking the thread<br>    return &quot;Data from $url&quot;<br>}</pre><ul><li>The suspend keyword marks the function as a suspending function.</li><li>delay(1000) suspends the function without blocking the main thread.</li><li>The function can only be called from another suspend function or within a coroutine.</li></ul><h4>How does suspend functions work internally?</h4><p>When the Kotlin compiler processes a suspend function or when the Kotlin compiler encounters a suspendfunction, it transforms the function using a technique called <strong><em>Continuation-Passing Style (CPS) </em></strong>to manage asynchronous execution<strong><em>.</em></strong></p><ol><li><strong>Continuation Mechanism:</strong></li></ol><ul><li><strong>Suspend functions</strong> use a concept called <strong>continuations</strong>. When a suspend function is called, it doesn’t execute all at once. Instead, it may pause its execution and save its state at a certain point. This saved state is called a <strong>continuation</strong>.</li><li>The continuation allows the function to resume later from where it was paused, preserving the function’s state, local variables, and the execution context.</li></ul><pre>suspend fun fetchData(): String {<br>    delay(1000)  // Suspend here<br>    return &quot;Data&quot;<br>}</pre><p>When delay(1000) is called, the function suspends, and the continuation is saved. After 1000 milliseconds, the continuation resumes execution.</p><p><strong>2. State Machine:</strong></p><ul><li>The compiler generates a state machine for the suspend function. This state machine keeps track of the function’s execution state and manages the suspension and resumption process without blocking threads, ensuring efficient execution.</li></ul><p><strong>3. Coroutine Context:</strong></p><ul><li><strong>Coroutine context</strong> is used to manage which thread or dispatcher the coroutine should run on. When a suspend function is called, it’s executed within a coroutine context that handles switching between threads as needed.</li><li>For example, Dispatchers.IO can be used for offloading tasks to a background thread, while Dispatchers.Main is used for UI updates.</li></ul><pre>GlobalScope.launch(Dispatchers.IO) {<br>    val data = fetchData()  // fetchData is a suspend function<br>}</pre><blockquote><strong>Suspension</strong>: Saves the function’s state and allows it to pause without blocking the thread.</blockquote><blockquote><strong>Continuation</strong>: Resumes the function from where it was paused, preserving execution context.</blockquote><blockquote><strong>State Machine</strong>: Manages the function’s execution state transitions.</blockquote><blockquote><strong>Coroutine Context</strong>: Handles threading and dispatching, allowing seamless switching between different threads or dispatchers.</blockquote><h4>Here’s a step-by-step breakdown of how a <strong>suspend function</strong> works internally, along with code to illustrate each step:</h4><p>1.<strong> Suspend Function Declaration</strong></p><p>When you declare a <strong>suspend</strong> function, Kotlin generates a <strong>state machine</strong> that manages the suspension and resumption of the function.</p><pre>suspend fun fetchData(): String {<br>    delay(1000L) // Suspends the function for 1 second<br>    return &quot;Data fetched&quot;<br>}</pre><p><strong>2. Continuation Object Creation</strong></p><p>When a suspend function is invoked, Kotlin creates a <strong>Continuation</strong> object to keep track of the function’s state and manage its suspension and resumption. The continuation stores:</p><ul><li>The current state of the function (where it was paused).</li><li>The result or exception returned after suspension.</li></ul><p><strong>3. Suspension Point</strong></p><p>At certain points in the function, such as a delay or network operation, the function suspends. Instead of blocking the thread, the continuation object is passed along, allowing the thread to do other work.</p><p>For example, the delay(1000L) suspends the function and returns control to the caller:</p><pre>suspend fun fetchData(): String {<br>    // Step 1: The coroutine starts execution<br>    println(&quot;Coroutine started&quot;)<br>    <br>    // Step 2: The function suspends here and passes the continuation to the dispatcher<br>    delay(1000L)  <br>    <br>    // Step 3: Resumption after delay completes<br>    println(&quot;Coroutine resumed&quot;)<br>    <br>    return &quot;Data fetched&quot;<br>}</pre><p><strong>4. Resumption with Continuation</strong></p><p>Once the asynchronous operation (like delay) is completed, the continuation object is used to <strong>resume</strong> the coroutine. The function resumes execution from where it was suspended.</p><pre>continuation.resumeWith(Result.success(&quot;Data fetched&quot;))</pre><p>Here’s what happens internally:</p><ul><li>The function resumes from the suspension point (delay).</li><li>It proceeds to return the result: &quot;Data fetched&quot;.</li></ul><p><strong>5. State Machine Handling</strong></p><p>Kotlin compiles the suspend function into a <strong>state machine</strong>. Each suspend point in the function marks a different “state” in the function, and the continuation object ensures that the function resumes from the correct state after suspension.</p><p>For instance, this pseudo-code illustrates the state transitions</p><pre>fun fetchData(continuation: Continuation&lt;String&gt;) {<br>    when (continuation.state) {<br>        0 -&gt; {<br>            // Initial state: suspend the coroutine and wait<br>            continuation.state = 1<br>            delay(1000L)<br>        }<br>        1 -&gt; {<br>            // Resume state: continuation resumes after delay<br>            continuation.resumeWith(Result.success(&quot;Data fetched&quot;))<br>        }<br>    }<br>}</pre><p><strong>6. CoroutineDispatcher</strong></p><p>The coroutine may run on different threads. The <strong>CoroutineDispatcher</strong> decides where the coroutine resumes after suspension. For example, a network call might suspend the coroutine on an I/O thread, and then it might resume on the main thread after completion.</p><pre>launch(Dispatchers.IO) {<br>    val result = fetchData()<br>    withContext(Dispatchers.Main) {<br>        println(result) // Switch back to the main thread after suspension<br>    }<br>}</pre><h3>Summary of the Flow:</h3><ol><li><strong>Function Call</strong>: The suspend function is invoked.</li><li><strong>Continuation Object</strong>: A continuation is created to manage function state.</li><li><strong>Function Suspension</strong>: At suspend points, like delay(), the function pauses, passing the continuation to handle resumption.</li><li><strong>Asynchronous Operation</strong>: While suspended, the async task (e.g., network request) runs in the background.</li><li><strong>Continuation Resumption</strong>: Once the async task completes, the function resumes with the continuation object.</li><li><strong>Return Result</strong>: The function returns the final result when it resumes.</li></ol><h4>The Continuation interface has two main methods</h4><p>The Kotlin Continuation interface has <strong>two key components</strong> that drive coroutine suspension and resumption</p><p><strong>context: CoroutineContext</strong>:</p><ol><li>This property holds the <strong>context</strong> in which the coroutine is running.</li><li>The CoroutineContext carries important information like:</li></ol><ul><li>The dispatcher (Dispatchers.IO, Dispatchers.Main, etc.), which specifies which thread the coroutine will run on.</li><li>The <strong>job</strong> of the coroutine, which can be used to cancel or track the coroutine’s lifecycle.</li></ul><p>3. Every coroutine has a CoroutineContext, and this context is available throughout the coroutine&#39;s lifetime, influencing its behavior.</p><pre>interface Continuation&lt;in T&gt; {<br>    val context: CoroutineContext<br>    fun resumeWith(result: Result&lt;T&gt;)<br>}<br><br>// Coroutine context could specify whether to use Dispatchers.Main or IO<br>val context = Dispatchers.IO + CoroutineName(&quot;MyCoroutine&quot;)</pre><p>The context is critical because it ensures the coroutine resumes on the correct thread or pool (e.g., resuming on the main thread after a background task finishes).</p><p><strong>resumeWith(result: Result&lt;T&gt;)</strong>:</p><ol><li>This is the core method that <strong>resumes the coroutine</strong> from where it was suspended.</li></ol><p>2. When a coroutine hits a suspension point, the Continuation captures the current state and stores it.</p><p>3. Later, when the task that caused suspension is done (e.g., a network call completes), the resumeWith method is called with the <strong>result</strong> (either success or failure).</p><p>4. The result parameter is of type Result&lt;T&gt;, which is a sealed class that wraps either:</p><ul><li>Result.success(value): The success result with the returned value of type T.</li><li>Result.failure(exception): The failure result, which contains the exception that occurred.</li></ul><pre>fun &lt;T&gt; Continuation&lt;T&gt;.resumeWith(result: Result&lt;T&gt;) {<br>    if (result.isSuccess) {<br>        // Resume the coroutine with the result value<br>    } else {<br>        // Handle the exception if the result is a failure<br>    }<br>}</pre><ul><li>When resumeWith is called, the coroutine restores its previously suspended state (local variables, execution point, etc.) and continues execution from where it left off.</li><li>If the result is a failure, the coroutine handles the exception (via try/catch or CoroutineExceptionHandler).</li></ul><h4>Key Points:</h4><ul><li><strong>context</strong>: Manages the environment (thread, dispatcher, etc.) where the coroutine runs.</li><li><strong>resumeWith</strong>: Resumes the coroutine by providing either a success result (to continue execution) or a failure (to handle exceptions).</li></ul><pre>suspend fun fetchData(): String = suspendCoroutine { continuation -&gt;<br>    try {<br>        // Simulating a network call<br>        val data = &quot;Result from server&quot;<br>        continuation.resumeWith(Result.success(data))  // Resuming with success<br>    } catch (e: Exception) {<br>        continuation.resumeWith(Result.failure(e))     // Resuming with failure<br>    }<br>}</pre><h4>Here’s a textual representation of the Kotlin coroutine flow diagram:</h4><ul><li><strong>Coroutine Started</strong><br>↓</li><li><strong>Suspend Function Called</strong><br>↓</li><li><strong>Suspension Point Reached</strong><br>↓</li><li><strong>Coroutine Suspended</strong><br>(Thread is free to execute other tasks)<br>↓</li><li><strong>Other Tasks Executed</strong><br>(Coroutine remains paused)<br>↓</li><li><strong>Suspended Task Completes</strong><br>↓</li><li><strong>Coroutine Resumed</strong><br>(Execution continues from where it was suspended)<br>↓</li><li><strong>Coroutine Completes</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*B61O64lTjSGZCrBwI2u5TA.png" /></figure><h4>Behavior in Multithreaded Context</h4><h4>1. Non-Blocking Nature of Suspend Functions:</h4><ul><li><strong>Suspend functions do not block the underlying thread</strong>, even when performing long-running tasks. This is a key difference from traditional multithreading approaches.</li><li>When a suspend function hits a suspension point (e.g., delay, withContext, I/O operations), it <strong>suspends the execution of the coroutine</strong> while freeing the thread it was running on.</li></ul><h4>2. Thread Management:</h4><ul><li>When a coroutine suspends, the <strong>thread it was running on is released</strong> to handle other tasks. This means the thread is not blocked waiting for the suspension to end, which leads to more efficient use of resources in multithreaded environments.</li><li>After the suspension ends (e.g., after a delay or network call completes), the coroutine resumes, potentially on <strong>a different thread</strong> depending on the dispatcher used.</li></ul><p>For example:</p><ul><li><strong>Dispatchers.IO</strong>: Coroutine may run on a different thread from a pool of threads optimized for I/O operations.</li><li><strong>Dispatchers.Default</strong>: Coroutine may resume on a thread from the default thread pool optimized for CPU-bound tasks.</li></ul><h4>3. Suspension and Resumption on Different Threads:</h4><ul><li>In multithreaded environments, it is common for a coroutine to <strong>suspend on one thread and resume on another</strong>. This behavior is controlled by the <strong>dispatcher</strong>.</li><li>For example:</li><li>A coroutine might start on a <strong>main thread</strong> (UI thread), then call withContext(Dispatchers.IO) to offload a heavy I/O operation to a background thread.</li><li>After the operation completes, the coroutine might resume back on the <strong>main thread</strong> (via withContext(Dispatchers.Main)), ensuring the UI can be updated safely.</li></ul><pre>GlobalScope.launch(Dispatchers.Main) {<br>    val result = withContext(Dispatchers.IO) {<br>        // Heavy I/O work (e.g., database or network call)<br>    }<br>    // Now we&#39;re back on the Main thread to update UI<br>}</pre><p>In this example:</p><ul><li>The coroutine starts on the main thread, then <strong>suspends</strong> when the heavy I/O operation starts in the background.</li><li>The main thread is freed while the I/O thread works. Once the I/O task finishes, the coroutine <strong>resumes</strong> on the main thread to continue its execution.</li></ul><h4>What Are Chained Suspend Functions?</h4><p>When you call one suspend function after another (in sequence), this is called <strong>chaining</strong> suspend functions. The next function waits until the previous one is done before it can start. They are connected like a chain.</p><pre>import kotlinx.coroutines.*<br><br>suspend fun fetchDataFromNetwork(): String {<br>    delay(1000) // Pause for 1 second (simulating a network request)<br>    return &quot;Network Data&quot; // Return data after 1 second<br>}<br><br>suspend fun processData(data: String): String {<br>    delay(500) // Pause for 0.5 seconds (simulating data processing)<br>    return &quot;Processed $data&quot; // Return processed data<br>}<br><br>suspend fun displayData(data: String) {<br>    delay(200) // Pause for 0.2 seconds (simulating data display delay)<br>    println(data) // Print the processed data<br>}<br><br>fun main() = runBlocking {<br>    val networkData = fetchDataFromNetwork()   // Step 1: Fetch data<br>    val processedData = processData(networkData) // Step 2: Process data<br>    displayData(processedData) // Step 3: Display data<br>}</pre><p><strong>Step 1: Fetch Data</strong> (fetchDataFromNetwork()):</p><ul><li>The function starts by simulating a network request with delay(1000) (which pauses the coroutine for 1 second).</li><li>After 1 second, the function returns &quot;Network Data&quot;.</li></ul><p><strong>What happens</strong>: The coroutine is paused for 1 second, and the thread is free to do other things during this time. After 1 second, the function resumes and returns the network data.</p><p><strong>Step 2: Process Data</strong> (processData(networkData)):</p><ul><li>After fetching the data, the coroutine calls processData() and passes &quot;Network Data&quot; to it.</li><li>Inside processData(), it simulates data processing with delay(500) (pauses the coroutine for 0.5 seconds).</li><li>After 0.5 seconds, the function returns &quot;Processed Network Data&quot;.</li></ul><p><strong>What happens</strong>: The coroutine is paused again for 0.5 seconds, and after that, it resumes and returns the processed data.</p><p><strong>Step 3: Display Data</strong> (displayData(processedData)):</p><ul><li>Now the coroutine passes &quot;Processed Network Data&quot; to displayData().</li><li>Inside displayData(), it simulates a delay of 0.2 seconds (as if it&#39;s preparing the display).</li><li>After 0.2 seconds, it prints &quot;Processed Network Data&quot;.</li></ul><p><strong>What happens</strong>: The coroutine is paused one last time for 0.2 seconds. After the pause, it prints the final result to the console.</p><h4>Visual Flow:</h4><ol><li>Start -&gt; <strong>fetchDataFromNetwork</strong> (Wait for 1 second) -&gt; Return &quot;Network Data&quot;.</li><li>Call <strong>processData</strong> (Wait for 0.5 seconds) -&gt; Return &quot;Processed Network Data&quot;.</li><li>Call <strong>displayData</strong> (Wait for 0.2 seconds) -&gt; Print &quot;Processed Network Data&quot;.</li></ol><h4>How Chaining Works:</h4><ul><li>Each function waits for the previous one to finish:</li><li><strong>processData()</strong> waits for <strong>fetchDataFromNetwork()</strong> to return.</li><li><strong>displayData()</strong> waits for <strong>processData()</strong> to return.</li><li>Kotlin’s coroutines handle the “waiting” part with <strong>suspension</strong> (using delay), which means the thread isn’t blocked. It can perform other tasks while waiting for the suspension to finish.</li></ul><ol><li><strong>What happens if a </strong><strong>suspend function is called on a thread and a suspension point is hit? Does it block the thread? How does it manage the thread once the suspension is over?</strong></li></ol><p>A suspend function doesn’t block the thread when it hits a suspension point. Instead, the coroutine’s state is saved, and the thread is freed for other work. When the task completes, the coroutine resumes on the thread specified by the dispatcher, not necessarily the same thread it was suspended on.</p><p><strong>2. How does chaining multiple </strong><strong>suspend functions work under the hood? What happens if one suspend function calls another, and both hit suspension points?</strong></p><p>When one suspend function calls another, the current function is suspended, and the Continuation object for the calling function is stored. The suspension propagates up the chain until all functions resume. Each suspend function has its own continuation that tracks where to resume after the suspension is over.</p><p><strong>3. What happens if you try to call a </strong><strong>suspend function inside a regular function without using a coroutine? Can you invoke a </strong><strong>suspend function outside of a coroutine context?</strong></p><p>You cannot directly call a suspend function inside a regular function because it requires a coroutine to manage its suspension. However, you can invoke a suspend function by wrapping it in a coroutine using runBlocking or starting a new coroutine scope.</p><p><strong>4. How are exceptions handled in a </strong><strong>suspend function? If an exception is thrown during the suspension, what happens to the continuation? Does it resume or abort the coroutine?</strong></p><p>If an exception is thrown in a suspend function, the continuation is resumed with the failure (Result.failure). The exception can be caught using a try-catch block within the coroutine. If not caught, the coroutine fails, and its exception is handled by the CoroutineExceptionHandler or propagated to the parent coroutine.</p><p><strong>5.Is it possible to call a non-suspend function from a suspend function? If so, what impact does this have on the suspension behavior?</strong></p><p>Yes, you can call a non-suspend function from a suspend function without any issues. However, calling a non-suspend function does not introduce any suspension points, so the coroutine will continue executing without being paused unless it encounters a suspend function later.</p><p><strong>6. What happens if a </strong><strong>suspend function is suspended but the result it was waiting for is never delivered (e.g., an infinite delay or network timeout)? How does the coroutine handle this situation?</strong></p><p>If the result never arrives (for example, the coroutine is suspended indefinitely due to an infinite delay or a network request that never completes), the coroutine remains suspended. You can use a timeout mechanism (like withTimeout()) to ensure that the coroutine is cancelled after a certain period if no result is received.</p><p><strong>7.How does suspension and resumption behave in nested coroutine scopes? What happens if a </strong><strong>suspend function is called in a child coroutine and the parent coroutine is cancelled?</strong></p><p>If a parent coroutine is cancelled, all its child coroutines are also cancelled. If a child coroutine calls a suspend function and the parent cancels before the function resumes, the child coroutine will be cancelled, and the suspension will not complete. All suspended child coroutines are aborted when the parent is cancelled.</p><p><strong>8. Can you pass a </strong><strong>suspend function as a parameter to a higher-order function? How does Kotlin handle the suspension within such a function?</strong></p><p>Yes, you can pass a suspend function as a parameter to a higher-order function. Kotlin allows higher-order functions to have suspend function types. The higher-order function itself must be a suspend function to call the suspend function parameter and handle the suspension correctly.</p><p><strong>9. Does using a </strong><strong>suspend function introduce additional performance overhead compared to non-suspend functions? If so, where does this overhead come from?</strong></p><p>Yes, suspend functions introduce some overhead because they involve creating and maintaining the Continuation object, as well as transforming the function into a state machine. However, this overhead is typically small and worth the trade-off for non-blocking asynchronous operations. The exact overhead depends on how many suspension points and coroutine dispatching mechanisms are involved.</p><p><strong>10. What happens if a coroutine is cancelled while a </strong><strong>suspend function is in progress? How is the </strong><strong>Continuation affected, and what happens to the coroutine’s state?</strong></p><p>If a coroutine is cancelled while a suspend function is in progress, the coroutine will not resume when the suspend function completes. The cancellation signal will cause the Continuation to stop, and an exception (CancellationException) will be thrown. The coroutine is then aborted, and its resources are cleaned up.</p><p>Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98ebbbd3bd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>