<?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 Ujjwal Kumar Maharana on Medium]]></title>
        <description><![CDATA[Stories by Ujjwal Kumar Maharana on Medium]]></description>
        <link>https://medium.com/@ujjwalkr.maharana?source=rss-ec0ea33d24c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KLciQJyQRtAgUk-gFyazfg.jpeg</url>
            <title>Stories by Ujjwal Kumar Maharana on Medium</title>
            <link>https://medium.com/@ujjwalkr.maharana?source=rss-ec0ea33d24c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:04:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ujjwalkr.maharana/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[Parallel Processing in Kotlin: Improving Map & Filter Performance with Coroutines]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/parallel-processing-in-kotlin-improving-map-filter-performance-with-coroutines-1dfcdac33b84?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dfcdac33b84</guid>
            <category><![CDATA[kotlin-tips]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 17:58:42 GMT</pubDate>
            <atom:updated>2025-03-31T03:35:31.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPkRzIelc-dL6KajX271eQ.jpeg" /></figure><p>Kotlin provides powerful collection functions like map and filter, which make transformations and filtering operations easy and readable. However, these operations are executed sequentially, which can become a bottleneck when dealing with large datasets or expensive operations such as database queries, network calls, or heavy computations.</p><p>To solve this, I implemented parallelMap and parallelFilter using Kotlin coroutines, allowing these operations to run in parallel. This approach can significantly reduce execution time when working with time-intensive tasks on large lists. However, it’s important to use them judiciously, as coroutine overhead and context switching can sometimes make them less efficient than their sequential counterparts for simple operations.</p><pre>suspend fun &lt;A&gt; Iterable&lt;A&gt;.parallelFilter(predicate: suspend (A) -&gt; Boolean): List&lt;A&gt; =<br>    coroutineScope {<br>        withContext(Dispatchers.IO) {<br>            this@parallelFilter.map { iterableData -&gt;<br>                async { Pair(iterableData, predicate(iterableData)) }<br>            }<br>                .map { deferred -&gt; deferred.await() }<br>                .filter { pair -&gt; pair.second }<br>                .map { pair -&gt; pair.first }<br>        }<br>    }</pre><pre>suspend fun &lt;A, B&gt; Iterable&lt;A&gt;.parallelMap(f: suspend (A) -&gt; B): List&lt;B&gt; = coroutineScope {<br>    map { async(Dispatchers.IO) { f(it) } }.awaitAll()<br>}</pre><p><strong>✅ Use Parallel Processing When:</strong></p><ol><li>Each map or filter operation is computationally expensive (e.g., database queries, API calls, or complex calculations).</li><li>The dataset is large enough that sequential execution takes considerable time.</li><li>Operations are independent &amp; do not depend on other items.</li></ol><p>🚀<strong> Impact of using this function:</strong></p><pre>@Test<br>fun testParallelMap() = runBlocking {<br>    val input = (1..1000).toList()<br><br>    val timeTakenForNormalMap = measureTimeMillis {<br>        input.map {<br>            // signifying time consuming operation<br>            delay(300.milliseconds)<br>            it * 2<br>        }<br>    }<br><br>    val timeTakenForParallelMap = measureTimeMillis {<br>        input.parallelMap {<br>            // signifying time consuming operation<br>            delay(300.milliseconds)<br>            it * 2<br>        }<br>    }<br><br>    println(&quot;Time taken for normal map: $timeTakenForNormalMap ms&quot;)<br>    println(&quot;Time taken for parallel map: $timeTakenForParallelMap ms&quot;)<br>    assert(timeTakenForNormalMap &gt; timeTakenForParallelMap)<br>}</pre><p>In the above case:<br>Normal map : 302464 ms &amp; parallelMap : 492 ms</p><p>By leveraging Kotlin coroutines, we can parallelize expensive map and filter operations, reducing execution time for large datasets. However, this approach should be used wisely, considering the trade-offs of coroutine overhead and parallel execution complexity.</p><p>If you’re dealing with performance bottlenecks due to sequential list operations, give parallelMap and parallelFilter a try and see the difference.</p><p>Thank you for reading. Any feedback / questions are welcomed. <br>You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a><em>. <br></em>Check out more interesting articles published by me <a href="https://medium.com/@ujjwalkr.maharana">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfcdac33b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLite: The Tiny Giant Powering the Digital World]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/sqlite-the-tiny-giant-powering-the-digital-world-62af17f22d82?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/62af17f22d82</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[tech-facts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tech-history]]></category>
            <category><![CDATA[database-optimization]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 04:52:42 GMT</pubDate>
            <atom:updated>2025-03-30T11:41:28.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*bgNl36x6OL9uEP3vK14Xyw.png" /></figure><p>Ever wondered why some apps feel lightning-fast even in areas with poor network connectivity, while others struggle without a stable internet connection? Apps like Swiggy, Zomato, and Flipkart are typically used in homes or offices, where users have access to high-speed internet. But then there are apps like WhatsApp, UPI apps, and messaging platforms that need to function seamlessly anywhere — whether in a crowded metro, a remote village, or inside an elevator with weak signal strength. The secret behind their speed and reliability? <strong>SQLite</strong> — the lightweight, self-contained database that powers countless applications behind the scenes. Despite its small footprint, SQLite plays a massive role in ensuring smooth user experiences, even in poor network connectivity. Let’s dive into some amazing and fun facts about SQLite that make it a silent yet indispensable part of our digital lives.</p><p>This project is also an engineering marvel, showcasing one of the finest engineering solutions ever executed.</p><ol><li>SQLite is maintained by three people. They don’t allow outside contributions.</li><li>SQLite is likely used more than all other database engines combined. Billions and billions of copies of SQLite exist in the wild. It’s everywhere. There are over one trillion (10,00,00,00,00,000 or a million million) SQLite databases in active use.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXZ6XTqn5aLcYl8XZd0AlA.png" /></figure><p>3. It is also probably one of the top five most deployed software modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5N5K3emzfcOYJmFVrJkfw.png" /></figure><p>4. SQLite originated from a US warship. D. Richard Hipp (DRH) was building software for the USS Oscar Austin, a Navy destroyer. The existing software would just stop working whenever the server went down (this was in the 2000s). For a battleship, this was unacceptable.</p><p>So DRH asked the question: what if the database just worked without any server? In DRH words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1woDu0WuhPFKxUibzH0rfA.png" /></figure><p>5. Unlike most open source project that uses standard licenses (like MIT or GPL), SQLite does not come with a OSI-approved license. Instead, SQLite is released into the public domain and it has even fewer restrictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-d9mhm4WcZgg1OV5xte3MQ.png" /></figure><p>6. They don’t allow outside contributions. You <em>cannot</em> just send a pull request and hope the patch will be accepted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxbPAJflrRTR54ReEogf5g.png" /></figure><p>7. There are over 600 lines of test code for every line of code in SQLite. Tests cover 100% of branches (and 100% <a href="https://en.wikipedia.org/wiki/Modified_condition/decision_coverage">MC/DC</a>) in the library. The test suite is extremely diverse, including fuzz tests, boundary value tests, regression tests, and tests that simulate operating system crashes, power losses, I/O errors, and out-of-memory errors.</p><p>8. SQLite does not have a Code of Conduct (CoC), rather <a href="https://sqlite.org/codeofethics.html">Code of Ethics</a> derived from “instruments of good works” from chapter 4 of The Rule of St. Benedict</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS3nAK0CfAjyvj2LG7_Oqg.png" /></figure><p>9. In SQLite: In place of a legal notice, here is a <a href="https://github.com/sqlite/sqlite/blob/624cb96/src/wal.c#L4,#L9">blessing</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*_c0m8jQ4E17M06M3bYq9wQ.png" /></figure><p>10. SQLite is so fast, they compete with fopen. For some use cases, you can use SQLite instead of a filesystem, that can be 35% faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*GyLiiwQ1F7m7nheYtND4KQ.png" /></figure><p>11. This is one my <a href="https://x.com/iavins/status/1865746403072389612">favorite lore</a>. SQLite had to change the default prefix from sqlite_ to etilqs_ when users started calling developers in the middle of the night</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*18IvfxUPD3bK_lG1vKI1hw.png" /></figure><p>12. SQLite takes backward compatibility very seriously</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9P4gPkm_aQUtjIAgAVZ3Q.png" /></figure><p>13. They take backward compatibility so seriously that even if they have <a href="https://x.com/iavins/status/1851276312876326980">shipped a bug</a>, they won’t fix it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*kiXCy_l6V32r1yBpumgQgg.png" /></figure><p>14. SQLite’s author D. Richard Hipp (DRH) did not find existing version control systems suitable. So he wrote his own called <a href="https://fossil-scm.org/home/doc/trunk/www/fossil-v-git.wiki">Fossil</a>. Fossil is powered by SQLite, of course. DRH wrote the B-Tree based on the algorithm in the book TAOCP by Donald Knuth, coding it on a plane while traveling</p><p>15. There are a few quirks, caveats &amp; gotchas in <a href="https://www.sqlite.org/quirks.html">SQLite</a></p><ul><li>The default is rollback journal mode, which restricts you to have either multiple readers or a single writer</li><li>Foreign Keys are disabled; they are opt-in</li><li>It is “weakly typed”. SQLite calls it “type affinity”. Meaning you can insert whatever in a column even though you have defined a type. Strong typed columns are opt-in (by <a href="https://www.sqlite.org/stricttables.html">STRICT</a> tables).</li><li><a href="https://sqlite.org/omitted.html">Many of the </a><a href="https://sqlite.org/omitted.html">ALTER commands</a> you expect in other databases don’t work. For example, you cannot add a contraint to an existing column. (They recently added ability to rename a column name)</li><li>SQLite has five types: NULL, INTEGER, REAL, TEXT, BLOB. Want to know something cursed? The type affinity works by <a href="https://www.sqlite.org/datatype3.html#determination_of_column_affinity">substring match</a>!</li></ul><p>SQLite is a powerful yet lightweight database. Its efficiency, speed, and reliability make it an ideal choice for app developers looking to improve user experience. With official libraries like <a href="https://developer.android.com/training/data-storage/room"><strong>Room for Android</strong></a> and <a href="https://github.com/ccgus/fmdb"><strong>FMDB for iOS</strong></a>, integrating SQLite into apps has never been easier. Whether you’re building a messaging app, a financial tool, or any application that requires offline support, SQLite ensures seamless data handling with minimal overhead. By leveraging this robust database, developers can create faster, more resilient applications that deliver a smooth user experience — anytime, anywhere. 🚀</p><p>Thank you for reading. Any feedback / questions are welcomed. <br>You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a><em>. <br></em>Check out more interesting articles published by me <a href="https://medium.com/@ujjwalkr.maharana">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62af17f22d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Kotlin Coroutines Series [Part 2]]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-2-ee0d22205c82?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0d22205c82</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 26 May 2024 12:46:44 GMT</pubDate>
            <atom:updated>2024-05-26T12:48:58.137Z</atom:updated>
            <content:encoded><![CDATA[<p>The entire series is divided into 3 sections:<br>1. <strong>Section 1</strong> — explains all the required usage of coroutines &amp; is recommended for everyone who are starting or just started using coroutines<br>2. <strong>Section 2</strong> — explains about exception handling &amp; cancellations &amp; is recommended for senior developers who already have good understanding of basics<br>3. <strong>Section 3</strong> — explains the detail working of how suspend function works under the hood &amp; is recommended for people who are very comfortable with all cases of section 1 &amp; 2</p><p>To keep the article readable in one sitting, I have divided it into 2 parts. Part 2 (this article) explains Section 2 &amp; Section 3, while for Section 1 please hop on to <a href="https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-1-01d5510fdf3f?source=friends_link&amp;sk=d7f9484a37efd23fa5c06e4acd26fe35">Part 1 of this series</a></p><figure><img alt="Kotlin Coroutines image taken from their official github repository" src="https://cdn-images-1.medium.com/max/1024/1*STDDIOqci9rs_e6VJ0oMrQ.png" /></figure><h3>Section 2</h3><h3>Cancellation in coroutines</h3><ol><li>Cancelling a parent scope cancels all its children</li></ol><pre>@Test<br>fun `cancelling scope cancels all its children`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val job1 = scope.launch {<br>        dummyTask1()<br>    }<br>    println(&quot;Job 1 is launched&quot;)<br><br>    val job2 = scope.launch {<br>        dummyTask2()<br>    }<br>    println(&quot;Job 2 is launched&quot;)<br><br>    delay(5000)<br><br>    println(&quot;Cancelling scope&quot;)<br>    scope.cancel()<br>    job1.join()<br>    job2.join()<br>}<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}</pre><blockquote>Both <em>job1</em> &amp; <em>job2</em> are launched in a parent <em>scope<br> </em>At T = 0, both jobs start their execution in parallel<br>At T = 5, parent scope is cancelled.<br>As soon as parent scope gets cancelled all children are cancelled</blockquote><p>Output will be</p><pre>Dummy task 1: 1<br>Job 1 is launched<br>Job 2 is launched<br>Dummy task 2: 1<br>Dummy task 2: 2<br>Dummy task 1: 2<br>Dummy task 1: 3<br>Dummy task 2: 3<br>Dummy task 1: 4<br>Dummy task 2: 4<br>Dummy task 1: 5<br>Dummy task 2: 5<br>Cancelling scope</pre><p>2. Cancelling one child doesn’t impact other siblings</p><pre>@Test<br>fun `cancelling child doesn&#39;t affect other siblings`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val job1 = scope.launch {<br>        dummyTask1()<br>    }<br>    println(&quot;Job 1 is launched&quot;)<br><br>    val job2 = scope.launch {<br>        dummyTask2()<br>    }<br>    println(&quot;Job 2 is launched&quot;)<br><br>    delay(5000)<br><br>    println(&quot;Cancelling job 1&quot;)<br>    job1.cancel()<br><br>    job1.join()<br>    job2.join()<br>}<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}</pre><blockquote>At T = 0, both the jobs start in parallel within same parent scope<br>At T = 5, <em>job1</em> is cancelled<br>But <em>job2</em> will continue its execution till it gets completed</blockquote><p>Output will be</p><pre>Job 1 is launched<br>Dummy task 1: 1<br>Job 2 is launched<br>Dummy task 2: 1<br>Dummy task 1: 2<br>Dummy task 2: 2<br>Dummy task 2: 3<br>Dummy task 1: 3<br>Dummy task 2: 4<br>Dummy task 1: 4<br>Dummy task 1: 5<br>Dummy task 2: 5<br>Cancelling job 1<br>Dummy task 2: 6<br>Dummy task 2: 7<br>Dummy task 2: 8<br>Dummy task 2: 9<br>Dummy task 2: 10<br>Dummy task 2 done</pre><p>3. Once a scope is cancelled, you cannot launch new coroutines in cancelled scope &amp; it fails silently without any warning/error</p><pre>@Test<br>fun `once a scope is cancelled you can&#39;t launch a new coroutine in that scope and it fails silently`() =<br>    runBlocking {<br>        val scope = CoroutineScope(context = Job())<br><br>        val job1 = scope.launch {<br>            dummyTask1()<br>        }<br>        println(&quot;Job 1 is launched&quot;)<br><br>        val job2 = scope.launch {<br>            dummyTask2()<br>        }<br>        println(&quot;Job 2 is launched&quot;)<br><br>        delay(5000)<br><br>        println(&quot;Cancelling scope&quot;)<br>        scope.cancel()<br><br>        val job3 = scope.launch {<br>            dummyTask3()<br>        }<br><br>        job1.join()<br>        job2.join()<br>        job3.join()<br>    }<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}<br><br>private suspend fun dummyTask3() {<br>    for (i in 1..10) {<br>        println(&quot;Dummy task 3: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 3 done&quot;)<br>}</pre><blockquote>At T = 0, <em>job1</em> &amp; <em>job2</em> start executing in parallel within the same parent scope<br>At T = 5, parent scope is cancelled &amp; hence all child jobs stop<br>At T = 5, new job is created on cancelled parent scope &amp; it neither executes nor gives any kind of error/warning</blockquote><p>Output will be</p><pre>Dummy task 1: 1<br>Job 1 is launched<br>Job 2 is launched<br>Dummy task 2: 1<br>Dummy task 2: 2<br>Dummy task 1: 2<br>Dummy task 1: 3<br>Dummy task 2: 3<br>Dummy task 2: 4<br>Dummy task 1: 4<br>Dummy task 2: 5<br>Dummy task 1: 5<br>Cancelling scope</pre><p>4. Cancellation of job is not like a disc brake. By default your job will continue to run even if its cancelled (there are ways to prevent this)</p><pre>@Test<br>fun `job cancel function&#39;s break failed`() = runBlocking {<br><br>    val scope = CoroutineScope(context = Job())<br>    val totalDurationInSeconds = 10<br><br>    val job = scope.launch {<br>        val startTime = System.currentTimeMillis()<br>        var nextPrintTime = startTime<br>        var i = 0<br>        while (i &lt; totalDurationInSeconds) {<br>            // print a message every second for 10 seconds<br>            if (System.currentTimeMillis() &gt;= nextPrintTime) {<br>                println(&quot;Dummy task 4: ${++i}&quot;)<br>                nextPrintTime += 1000L<br>            }<br>        }<br>    }<br>    println(&quot;Job is launched&quot;)<br><br>    delay(5000)<br>    println(&quot;5 seconds wait is completed. Now cancelling job&quot;)<br>    job.cancel()<br>    println(&quot;Job cancelled. Done!&quot;)<br>    job.join()<br>}</pre><blockquote>At T = 0, job starts in parallel which prints a message every second<br>At T = 5, job is cancelled but it still continues to run<br>This is because its the default behaviour of job cancellation</blockquote><p>Output will be</p><pre>Job is launched<br>Dummy task 4: 1<br>Dummy task 4: 2<br>Dummy task 4: 3<br>Dummy task 4: 4<br>Dummy task 4: 5<br>Dummy task 4: 6<br>5 seconds wait is completed. Now cancelling job<br>Job cancelled. Done!<br>Dummy task 4: 7<br>Dummy task 4: 8<br>Dummy task 4: 9<br>Dummy task 4: 10</pre><p>5. Cancellation of coroutines needs to be cooperative.</p><p>By cooperative, it means while executing a job from time to time it should check whether the parent scope is active or not. And if not active then it should not execute further.<br>There are majorly 3 ways this check is done:<br>A. suspend functions are cancellable <em>(Starting a new suspend function check for active job is done by default)</em><br>B. job.isActive() check can be added within a function which is going to be a long loop<br>C. ensureActive() can be called within a function</p><pre>@Test<br>fun `fixing job cancel function&#39;s break &amp; making it disc break`() = runBlocking {<br><br>    val scope = CoroutineScope(context = Job())<br>    val totalDurationInSeconds = 10<br><br>    val job = scope.launch {<br>        val startTime = System.currentTimeMillis()<br>        var nextPrintTime = startTime<br>        var i = 0<br>        while (i &lt; totalDurationInSeconds &amp;&amp; isActive) {<br>            // print a message every second for 10 seconds<br>            if (System.currentTimeMillis() &gt;= nextPrintTime) {<br>                println(&quot;Dummy task 4: ${++i}&quot;)<br>                nextPrintTime += 1000L<br>            }<br>        }<br>    }<br>    println(&quot;Job is launched&quot;)<br><br>    delay(5000)<br>    println(&quot;5 seconds wait is completed. Now cancelling job&quot;)<br>    job.cancel()<br>    println(&quot;Job cancelled. Done!&quot;)<br>    job.join()<br>}</pre><blockquote>Example is same as above just that in while loop isActive condition is added<br>After job is cancelled, when flow reaches to while condition check isActive returns false &amp; further execution stops</blockquote><p>Output will be</p><pre>Dummy task 4: 1<br>Job is launched<br>Dummy task 4: 2<br>Dummy task 4: 3<br>Dummy task 4: 4<br>Dummy task 4: 5<br>Dummy task 4: 6<br>5 seconds wait is completed. Now cancelling job<br>Job cancelled. Done!</pre><h3>Exceptions in coroutines</h3><ol><li>When a coroutine fails with an exception, it propagates exception to its immediate parent. And the parent does the following<br>A. cancel rest of its children<br>B. cancel itself<br>C. propagate exception to its parent</li></ol><p>This chain of propagation &amp; cancellation continues till it reaches up to root of hierarchy &amp; all coroutine started gets cancelled</p><pre>@Test<br>fun `a child throwing an exception propagates the error &amp; cancels other children`() = runTest {<br>    val scope = CoroutineScope(context = Job())<br><br>    val job1 = scope.launch {<br>        dummyTask1()<br>    }<br><br>    val job2 = scope.launch {<br>        dummyTask2()<br>    }<br><br>    job1.join()<br>    job2.join()<br>}<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    println(&quot;Dummy task 2 started&quot;)<br>    delay(8000)<br>    println(&quot;Dummy task 2 finished&quot;)<br>}</pre><blockquote>At T = 0, both job start executing in parallel<br>At <em>job1.join()</em> line, at T = 5 <em>job1</em> throws exception &amp; entire flow gets cancelled &amp; exception is thrown<br>And even though task2 had no exception, it couldn’t fininsh</blockquote><p>Output will be</p><pre>Dummy task 2 started<br>Dummy task 1 started<br><br>java.lang.Exception: Dummy task 1 failed<br> at com.example.ExceptionTest.dummyTask1(ExceptionTest.kt:218)<br> at com.example.ExceptionTest.access$dummyTask1(ExceptionTest.kt:14)<br> at com.example.ExceptionTest$dummyTask1$1.invokeSuspend(ExceptionTest.kt)<br> at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)<br> at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)</pre><p>2. A special type of job called SupervisorJob exist. Its properties are<br>A. Failure of a child doesn’t affect other children<br>B. Won’t propagate the exception &amp; let the child coroutine handle it</p><p>This is used in cases where you don’t want a failure in one child coroutine to cancel the parent and siblings.</p><pre>@Test<br>fun `a child throwing an exception should not propagate error &amp; other children should continue working`() =<br>    runTest {<br>        val scope = CoroutineScope(context = SupervisorJob())<br><br>        val job1 = scope.launch {<br>            dummyTask1()<br>        }<br><br>        val job2 = scope.launch {<br>            dummyTask2()<br>        }<br><br>        val job3 = scope.launch {<br>            dummyTask3()<br>        }<br><br>        job1.join()<br>        job2.join()<br>        job3.join()<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    println(&quot;Dummy task 2 started&quot;)<br>    delay(8000)<br>    println(&quot;Dummy task 2 finished&quot;)<br>}<br><br>private suspend fun dummyTask3() {<br>    println(&quot;Dummy task 3 started&quot;)<br>    delay(2000)<br>    println(&quot;Dummy task 3 finished&quot;)<br>}</pre><blockquote>At T = 0, all 3 job start executing in parallel<br>At T = 2, job3 is completed<br>Main code flow will be at job1.join() from T = 0 to T = 5<br>At T = 5, job1 throws exception but as all these are launched in SupervisorJob all siblings will continue to execute as normal<br>From T = 5 to T = 8, main code flow will be at job2.join()<br>And at T = 8, entire code flow will complete<br>While task1 would throw exception, task2 &amp; task3 will finish</blockquote><p>Output will be</p><pre>Dummy task 1 started<br>Dummy task 3 started<br>Dummy task 2 started<br>Dummy task 3 finished<br>Dummy task 2 finished<br><br>java.lang.Exception: Dummy task 1 failed<br> at com.example.ExceptionTest.dummyTask1(ExceptionTest.kt:218)<br> at com.example.ExceptionTest.access$dummyTask1(ExceptionTest.kt:14)<br> at com.example.ExceptionTest$dummyTask1$1.invokeSuspend(ExceptionTest.kt)</pre><p>3. A scope created with SupervisorJob type or coroutines launched in a supervisorScope behave similar</p><pre>@Test<br>fun `a child throwing an exception should not propagate error &amp; other children should continue working using supervisor scope`() =<br>    runTest {<br>        val scope = CoroutineScope(context = Job())<br><br>        val job = scope.launch {<br>            supervisorScope {<br>                launch {<br>                    dummyTask1()<br>                }<br>                launch {<br>                    dummyTask2()<br>                }<br>                launch {<br>                    dummyTask3()<br>                }<br>            }<br><br>        }<br><br>        job.join()<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    println(&quot;Dummy task 2 started&quot;)<br>    delay(8000)<br>    println(&quot;Dummy task 2 finished&quot;)<br>}<br><br>private suspend fun dummyTask3() {<br>    println(&quot;Dummy task 3 started&quot;)<br>    delay(2000)<br>    println(&quot;Dummy task 3 finished&quot;)<br>}</pre><blockquote>All tasks are launched in supervisorScope. And behaviour will be exactly same if was launched using SupervisorJob<br>Task1 would throw exception, but task2 &amp; task3 will complete normally</blockquote><p>Output will be</p><pre>Dummy task 1 started<br>Dummy task 3 started<br>Dummy task 2 started<br>Dummy task 3 finished<br>Dummy task 2 finished<br><br>java.lang.Exception: Dummy task 1 failed<br> at com.example.ExceptionTest.dummyTask1(ExceptionTest.kt:218)<br> at com.example.ExceptionTest.access$dummyTask1(ExceptionTest.kt:14)<br> at com.example.ExceptionTest$dummyTask1$1.invokeSuspend(ExceptionTest.kt)<br> at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)<br> at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)</pre><p>4. A SupervisorJob only works as described when it’s part of a scope: either created using supervisorScope or CoroutineScope(SupervisorJob())<br>Passing a SupervisorJob as a parameter of a coroutine builder will not have the desired effect you would’ve thought for cancellation</p><pre>@Test<br>fun `SuperVisorJob should be part of scope, being part of coroutine builder does nothing`() =<br>    runTest {<br>        val scope = CoroutineScope(context = Job())<br><br>        val job = scope.launch(SupervisorJob()) {<br>            launch {<br>                dummyTask1()<br>            }<br>            launch {<br>                dummyTask2()<br>            }<br>            launch {<br>                dummyTask3()<br>            }<br>        }<br><br>        job.join()<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    println(&quot;Dummy task 2 started&quot;)<br>    delay(8000)<br>    println(&quot;Dummy task 2 finished&quot;)<br>}<br><br>private suspend fun dummyTask3() {<br>    println(&quot;Dummy task 3 started&quot;)<br>    delay(2000)<br>    println(&quot;Dummy task 3 finished&quot;)<br>}</pre><blockquote>This way of SupervisorJob will not work &amp; as soon as exception occurs in one child coroutine, it will cancel all sibling coroutines.<br>So task2 will not reach finish state, even though no exception occurred inside it<br>Task3 will finish because it finished before task1 threw exception</blockquote><p>Output will be</p><pre>Dummy task 1 started<br>Dummy task 3 started<br>Dummy task 2 started<br>Dummy task 3 finished<br><br>java.lang.Exception: Dummy task 1 failed<br> at com.example.ExceptionTest.dummyTask1(ExceptionTest.kt:218)<br> at com.example.ExceptionTest.access$dummyTask1(ExceptionTest.kt:14)<br> at com.example.ExceptionTest$dummyTask1$1.invokeSuspend(ExceptionTest.kt)<br> at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)<br> at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)</pre><h3>Handling of exceptions in coroutines</h3><p>Different type of exception handling is needed based on type of coroutine builders used.</p><ol><li>launch<br> — exceptions will be thrown as soon as they happen &amp; not on .join()<br> — wrap the code that can throw exceptions inside a try/catch</li></ol><p>2. async<br> — exceptions are not thrown automatically, instead, they’re thrown when you call .await()</p><p>3. CoroutineExceptionHandler<br> — optional element of a CoroutineContext allowing you to handle uncaught exceptions</p><h4>Examples to understand exception handling</h4><ol><li>launch throws exception as soon as they happen so it needs to be handled at launch itself and not at .join()</li></ol><pre>@Test<br>fun `launch throws exception as soon as they happen so it needs to be handled at launch itself else it fails`() =<br>    runTest {<br>        val scope = CoroutineScope(context = Job())<br>        val job = scope.launch {<br>            dummyTask1()<br>        }<br><br>        try {<br>            job.join()<br>        } catch (e: Exception) {<br>            println(&quot;Caught exception in join block with message: ${e.message}&quot;)<br>        }<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><blockquote>try-catch is added at job.join() which won’t work in this case</blockquote><p>Output will be</p><pre>Dummy task 1 started<br><br>java.lang.Exception: Dummy task 1 failed<br> at com.example.ExceptionTest.dummyTask1(ExceptionTest.kt:218)<br> at com.example.ExceptionTest.access$dummyTask1(ExceptionTest.kt:14)<br> at com.example.ExceptionTest$dummyTask1$1.invokeSuspend(ExceptionTest.kt)<br> at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)<br> at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)<br> at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)</pre><p>2. launch throws exception as soon as they happen so it needs to be handled at launch itself</p><pre>@Test<br>fun `launch throws exception as soon as they happen so it needs to be handled at launch itself`() =<br>    runTest {<br>        val scope = CoroutineScope(context = Job())<br>        val job = scope.launch {<br>            try {<br>                dummyTask1()<br>            } catch (e: Exception) {<br>                println(&quot;Caught exception in launch block with message: ${e.message}&quot;)<br>            }<br>        }<br><br>        try {<br>            job.join()<br>        } catch (e: Exception) {  // This is useless<br>            println(&quot;Caught exception in join block with message: ${e.message}&quot;)<br>        }<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><blockquote>try-catch added around launch will be sufficient &amp; will catch the exception</blockquote><p>Output will be</p><pre>Dummy task 1 started<br>Caught exception in launch block with message: Dummy task 1 failed</pre><p>3. async throws exception when await is called so can be handled later at await</p><pre>@Test<br>fun `async throws exception when await is called so can be handled later at await`() = runTest {<br>    val scope = CoroutineScope(context = Job())<br>    val job = scope.async {<br>        dummyTask1()<br>    }<br><br>    try {<br>        job.await()<br>    } catch (e: Exception) {<br>        println(&quot;Caught exception in await block with message: ${e.message}&quot;)<br>    }<br>}<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><p>Output will be</p><pre>Dummy task 1 started<br>Caught exception in await block with message: Dummy task 1 failed</pre><p>4. async throws exception when await is called but can be handled at async as well</p><pre>@Test<br>fun `async throws exception when await is called but can be handled at async as well`() =<br>    runTest {<br>        val scope = CoroutineScope(context = SupervisorJob())<br>        val job = scope.async {<br>            try {<br>                dummyTask1()<br>            } catch (e: Exception) {<br>                println(&quot;Caught exception in async block with message: ${e.message}&quot;)<br>            }<br>        }<br><br>        try {<br>            job.await()<br>        } catch (e: Exception) {<br>            println(&quot;Caught exception in await block with message: ${e.message}&quot;)<br>        }<br>    }<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><blockquote>In case of async, exception can be caught at scope.async as well as .await()<br>If added at both places the one added initially will catch the exception</blockquote><p>Output will be</p><pre>Dummy task 1 started<br>Caught exception in async block with message: Dummy task 1 failed</pre><p>5. coroutine exception handler to catch exception</p><pre>@Test<br>fun `coroutine exception handler to catch exception`() = runTest {<br>    val scope = CoroutineScope(context = Job())<br>    val handler = CoroutineExceptionHandler { coroutineContext, exception -&gt;<br>        println(&quot;Caught exception in custom handler with message: ${exception.message}&quot;)<br>    }<br><br>    val job = scope.launch(handler) {<br>        dummyTask1()<br>    }<br><br>    job.join()<br>}<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><p>Output will be</p><pre>Dummy task 1 started<br>Caught exception in custom handler with message: Dummy task 1 failed</pre><p>6. coroutine exception handler to catch exception at scope creation level</p><pre>@Test<br>fun `coroutine exception handler to catch exception at scope creation level`() = runTest {<br>    val handler = CoroutineExceptionHandler { coroutineContext, exception -&gt;<br>        println(&quot;Caught exception in custom handler with message: ${exception.message}&quot;)<br>    }<br>    val scope = CoroutineScope(context = Job() + handler)<br><br>    val job = scope.launch {<br>        dummyTask1()<br>    }<br><br>    job.join()<br>}<br><br>private suspend fun dummyTask1() {<br>    println(&quot;Dummy task 1 started&quot;)<br>    delay(5000)<br>    throw Exception(&quot;Dummy task 1 failed&quot;)<br>}</pre><p>Output will be</p><pre>Dummy task 1 started<br>Caught exception in custom handler with message: Dummy task 1 failed</pre><h4>Major difference in exceptions generated by launch &amp; async</h4><ol><li>In case of <em>launch()</em>, if exception is generated it will be thrown irrespective of whether you do <em>.join()</em> or use it as fire &amp; forget. Also exception handling needs to be around <em>scope.launch() {…}</em>. <br>And it will not get caught if done around <em>.join()</em></li><li>In case of <em>async()</em>, even if exception is generated it will <strong>not </strong>be thrown unless <em>.await()</em> is called. Also exception handling can be done at both around <em>scope.async() {…}</em> or around <em>.await()</em>. <br>If done around both, <em>scope.async() {…} </em>will be the place where it will get caught</li></ol><h4>Difference between runBlocking &amp; runTest coroutine</h4><ol><li>run blocking waits for all coroutines that are launched in this scope</li></ol><pre>@Test<br>fun `run blocking waits for all coroutines that are launched in this scope`() = runBlocking {<br>    val startTime = System.currentTimeMillis()<br>    launch {<br>        dummyTask1(startTime = startTime)<br>    }<br><br>    launch {<br>        dummyTask2(startTime = startTime)<br>    }<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000}&quot;)<br>}<br><br>private suspend fun dummyTask1(startTime: Long) {<br>    println(&quot;Starting dummy task 1&quot;)<br>    delay(3000)<br>    println(&quot;Finishing dummy task 1 at ${(System.currentTimeMillis() - startTime) / 1000}&quot;)<br>}<br><br>private suspend fun dummyTask2(startTime: Long) {<br>    println(&quot;Starting dummy task 2&quot;)<br>    delay(5000)<br>    println(&quot;Finishing dummy task 2 at ${(System.currentTimeMillis() - startTime) / 1000}&quot;)<br>}</pre><blockquote>Here we just launch 2 coroutines &amp; do not wait for their end. <br>But as these are launched in runBlocking scope, so after last line is executed it will wait till all coroutines launched in this scope are completed.<br>So at T = 0, 2 tasks are launched in parallel &amp; the main code flow reaches till last line at T = 0 itself. But after that before exiting the function, runBlocking waits for both the coroutines to complete</blockquote><p>Output will be</p><pre>Total time taken: 0<br>Starting dummy task 1<br>Starting dummy task 2<br>Finishing dummy task 1 at 3<br>Finishing dummy task 2 at 5</pre><p>2. run test waits for all coroutines that are launched in this scope and skips all delays</p><pre>@Test<br>fun `run test waits for all coroutines that are launched in this scope and skips all delays`() =<br>    runTest {<br>        val startTime = System.currentTimeMillis()<br>        launch {<br>            dummyTask1(startTime = startTime)<br>        }<br><br>        launch {<br>            dummyTask2(startTime = startTime)<br>        }<br>        val endTime = System.currentTimeMillis()<br>        println(&quot;Total time taken: ${(endTime - startTime) / 1000}&quot;)<br>    }<br><br>private suspend fun dummyTask1(startTime: Long) {<br>    println(&quot;Starting dummy task 1&quot;)<br>    delay(3000)<br>    println(&quot;Finishing dummy task 1 at ${(System.currentTimeMillis() - startTime) / 1000}&quot;)<br>}<br><br>private suspend fun dummyTask2(startTime: Long) {<br>    println(&quot;Starting dummy task 2&quot;)<br>    delay(5000)<br>    println(&quot;Finishing dummy task 2 at ${(System.currentTimeMillis() - startTime) / 1000}&quot;)<br>}</pre><blockquote>Any delays added inside runTest scope gets skipped.<br>And similar to runBlocking, it waits for all coroutines launched inside its scope to complete</blockquote><p>Output will be</p><pre>Total time taken: 0<br>Starting dummy task 1<br>Starting dummy task 2<br>Finishing dummy task 1 at 0<br>Finishing dummy task 2 at 0</pre><h3>Section 3</h3><h3>What is the magic behind suspend function</h3><ol><li>Compiler takes suspend functions and convert them to an optimised version of callbacks using a finite state machine [the compiler will write those callbacks for you]</li><li>suspend functions communicates with each other using <em>Continuation</em> objects</li></ol><pre>interface Continuation&lt;in T&gt; {<br>  public val context: CoroutineContext<br>  public fun resumeWith(value: Result&lt;T&gt;)<br>}</pre><p>3. Compiler replaces the suspend modifier with the extra parameter completion (of type <em>Continuation</em>) in the function signature that is used to communicate the result of the suspend function to the coroutine that called</p><p>4. When converting callback-based APIs to coroutines using suspendCoroutine, you directly interact with a <em>Continuation</em> object to resume the coroutine that got suspended after running the block of code passed as a parameter</p><p>5. There’s a subtype of Continuation called DispatchedContinuation whose resume function makes a dispatch call to the Dispatcher available in the CoroutineContext</p><h4>Let’s try to understand this process using a simple example</h4><p>Original code:</p><pre>suspend fun loginUser(userId: String, password: String): User {<br>  val user = userRemoteDataSource.logUserIn(userId, password)<br>  val userDb = userLocalDataSource.logUserIn(user)<br>  return userDb<br>}</pre><ol><li>1st step is compiler will add <em>Continuation</em> as last parameter of the function</li></ol><pre>fun loginUser(userId: String, password: String, completion: Continuation&lt;Any?&gt;) {<br>  val user = userRemoteDataSource.logUserIn(userId, password)<br>  val userDb = userLocalDataSource.logUserIn(user)<br>  completion.resume(userDb)<br>}</pre><p>2. 2nd step is breaking this function into finite states. The compiler can then execute 1 or more states, store all the required results, suspend(pause) this function execution, execute some other function and come back again to execute next states reusing results of previous states.</p><p>In the example that we have taken, it can be broken into 3 finite states</p><pre>fun loginUser(userId: String, password: String, completion: Continuation&lt;Any?&gt;) {<br>  when(label) {<br>    0 -&gt; { // Label 0 -&gt; first execution<br>        userRemoteDataSource.logUserIn(userId, password)<br>    }<br>    1 -&gt; { // Label 1 -&gt; resumes from userRemoteDataSource<br>        userLocalDataSource.logUserIn(user)<br>    }<br>    2 -&gt; { // Label 2 -&gt; resumes from userLocalDataSource<br>        completion.resume(userDb)<br>    }<br>    else -&gt; throw IllegalStateException(...)<br>  }<br>}</pre><p>3. After this compiler creates a private class to hold the required data and call the functions(states)</p><pre>fun loginUser(userId: String?, password: String?, completion: Continuation&lt;Any?&gt;) {<br>  class LoginUserStateMachine(<br>    // completion parameter is the callback to the function <br>    // that called loginUser<br>    completion: Continuation&lt;Any?&gt;<br>  ): CoroutineImpl(completion) {<br>    // Local variables of the suspend function<br>    var user: User? = null<br>    var userDb: UserDb? = null<br>    // Common objects for all CoroutineImpls<br>    var result: Any? = null<br>    var label: Int = 0<br>    // this function calls the loginUser again to trigger the<br>    // state machine (label will be already in the next state) and<br>    // result will be the result of the previous state&#39;s computation<br>    override fun invokeSuspend(result: Any?) {<br>      this.result = result<br>      loginUser(null, null, this)<br>    }<br>  }<br>  ...<br>}</pre><p>4. In the next step compiler adds information on how to move between states &amp; maintain for which state it is being called. This is done by checking the value from continuation</p><pre>fun loginUser(userId: String?, password: String?, completion: Continuation&lt;Any?&gt;) {<br>  ...<br>  val continuation = completion as? LoginUserStateMachine ?: LoginUserStateMachine(completion)<br>  ...<br>}</pre><p>5. Here is the sample code post generation of finite state machine for our <em>loginUser</em> function</p><pre>fun loginUser(userId: String?, password: String?, completion: Continuation&lt;Any?&gt;) {<br>    ...<br><br>    val continuation = completion as? LoginUserStateMachine ?: LoginUserStateMachine(completion)<br><br>    when(continuation.label) {<br>        0 -&gt; {<br>            // Checks for failures<br>            throwOnFailure(continuation.result)<br>            // Next time this continuation is called, it should go to state 1<br>            continuation.label = 1<br>            // The continuation object is passed to logUserIn to resume <br>            // this state machine&#39;s execution when it finishes<br>            userRemoteDataSource.logUserIn(userId!!, password!!, continuation)<br>        }<br>        1 -&gt; {<br>            // Checks for failures<br>            throwOnFailure(continuation.result)<br>            // Gets the result of the previous state<br>            continuation.user = continuation.result as User<br>            // Next time this continuation is called, it should go to state 2<br>            continuation.label = 2<br>            // The continuation object is passed to logUserIn to resume <br>            // this state machine&#39;s execution when it finishes<br>            userLocalDataSource.logUserIn(continuation.user, continuation)<br>        }<br>        2 -&gt; {<br>            // Checks for failures<br>            throwOnFailure(continuation.result)<br>            // Gets the result of the previous state<br>            continuation.userDb = continuation.result as UserDb<br>            // Resumes the execution of the function that called this one<br>            continuation.cont.resume(continuation.userDb)<br>        }<br>}</pre><p>6. The Kotlin compiler transforms every suspend function to be a state machine, which optimises using callbacks every time a function needs to suspend</p><p>7. How the code can suspend without blocking threads: the information of what needs to be executed when the function is resumed is stored in the Continuation object</p><p>Want to know about how coroutine was ideated &amp; designed.<br><a href="https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md">Follow this link</a></p><p>Thank you for reading till the end. This marks the end of the series. Hope you enjoyed learning kotlin coroutines. If you have any questions / queries, feel free to add a comment &amp; I will try to answer it as early as possible.<br>To refresh on basics of coroutines, here is the <a href="https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-1-01d5510fdf3f?source=friends_link&amp;sk=d7f9484a37efd23fa5c06e4acd26fe35">link to Part 1 of the article</a></p><p>Thank you for reading. Any feedback / questions are welcomed. You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0d22205c82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Kotlin Coroutines Series [Part 1]]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-1-01d5510fdf3f?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/01d5510fdf3f</guid>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 26 May 2024 12:46:39 GMT</pubDate>
            <atom:updated>2024-05-26T12:50:34.069Z</atom:updated>
            <content:encoded><![CDATA[<p>A <em>coroutine</em> is a concurrency design pattern to simplify code that executes asynchronously. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one.</p><p>Coroutines can be thought of as light-weight threads, but there is a number of important differences that make their real-life usage very different from threads. Coroutines are less resource-intensive than JVM threads.</p><p>This article is explains the fundamentals, terminologies &amp; an exhaustive set of code examples. <br>The entire series is divided into 3 sections:<br>1. <strong>Section 1</strong> — explains all the required usage of coroutines &amp; is recommended for everyone who are starting or just started using coroutines<br>2. <strong>Section 2</strong> — explains about exception handling &amp; cancellations &amp; is recommended for senior developers who already have good understanding of basics<br>3. <strong>Section 3</strong> — explains the detail working of how suspend function works under the hood &amp; is recommended for people who are very comfortable with all cases of section 1 &amp; 2</p><p>To keep the article readable in one sitting, I have divided it into 2 parts. Part 1 (this article) explains Section 1, while for Section 2 &amp; Section 3 please hop on to <a href="https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-2-ee0d22205c82?source=friends_link&amp;sk=84e7e550600921d3adf0883b7ce883d0">Part 2 of this series</a>.</p><p>This article is meant for very practical usage &amp; understanding and has lots of code examples. Make sure to copy the code &amp; run in your IDE in case you face difficulty in understanding any example. Also each example builds on learnings from previous examples, so do follow all the examples in sequence.</p><figure><img alt="Kotlin Coroutines image taken from their official github repository" src="https://cdn-images-1.medium.com/max/1024/1*STDDIOqci9rs_e6VJ0oMrQ.png" /></figure><h3>Section 1</h3><h3><strong>Coroutines Basics</strong></h3><h4>Advantages:</h4><ol><li>Light weight — Less resource intensive than JVM threads hence takes lesser memory</li><li>Suspending &amp; resuming mid way — When executing a suspend function, a coroutine can pause the execution of a function mid-way, execute some other function &amp; come back &amp; resume the execution of original function</li><li>Synchronous by looks, asynchronous by functionality — Writing complex asynchronous code is very clean &amp; seamless using coroutines</li></ol><h3>Components of Coroutines</h3><h4>CoroutineScope</h4><ol><li>Keeps track of any coroutine you create using <em>launch</em> or <em>async</em></li><li>Ongoing work (running coroutines) can be canceled by calling <em>scope.cancel()</em> at any point in time</li><li>You should create a <em>CoroutineScope</em> whenever you want to start and control the lifecycle of coroutines</li><li>When creating a <em>CoroutineScope</em> it takes a <em>CoroutineContext</em> as a parameter to its constructor</li></ol><pre>val scope = CoroutineScope(Job() + Dispatchers.Main)<br>val job = scope.launch {<br>    // new coroutine<br>}</pre><blockquote>Note: There exists some special coroutineScope in Android framework such as ViewModelScope, LifecycleScope etc. These coroutine scopes have inbuilt handling of cancelling all child jobs when the corresponding parent (viewmodel / activity) gets destroyed. More on job cancellation below</blockquote><h4>Job</h4><ol><li>A Job is a handle to a coroutine</li><li>Every coroutine that you create (by launch or async), it returns a Job instance that uniquely identifies the coroutine and manages its lifecycle</li><li>Lifecyle of a Job: New, Active, Completing, Completed, Cancelling and Cancelled</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*80MjvLtbJSRY2VKX" /></figure><h4>CoroutineContext</h4><ol><li>Set of elements that define the behaviour of a coroutine</li><li>It consists of 3 components:</li></ol><p>A. <em>Job</em> — controls the lifecycle of the coroutine<br>B. <em>CoroutineDispatche</em>r — dispatches work to the appropriate <em>thread <br></em>C. <em>CoroutineExceptionHandler</em> — handles uncaught exceptions</p><p>You can create coroutine inside a coroutine</p><pre>val scope = CoroutineScope(Job() + Dispatchers.IO)<br>val job = scope.launch {<br>    // New coroutine that has CoroutineScope as a parent<br>    val result = async {<br>        // New coroutine that has the coroutine started by <br>        // launch as a parent<br>    }.await()<br>}</pre><h4>CoroutineBuilders</h4><ol><li><em>launch<br></em>A. Returns a Job and does not carry any resulting value<br>B. Used in case of fire &amp; forget flow</li></ol><p>2. <em>async<br> </em>A. Returns an instance of <em>Deferred&lt;T&gt;</em>, which has an <em>.await()</em> function that returns the result of the coroutine<br> B. Used in cases where we need to perform a task &amp; return a result from it</p><p>3. <em>withContext<br></em>A. Does not create a new coroutine, it only shifts the context of the existing coroutine to some other dispatcher which is provided in its constructor parameter</p><h4>Dispatchers</h4><p>Determines what thread or threads the corresponding coroutine uses for its execution</p><ol><li>Dispatcher.IO — Designed for handling blocking I/O operations like reading files, making network requests, or accessing databases. It has a minimum limit of 64 threads providing plenty of bandwidth for concurrent I/O tasks</li><li>Dispatcher.Default — Designed for handling CPU-intensive tasks. It uses a thread pool with count equivalent to number of CPU cores in your machine, with a minimum of 2 threads</li><li>Dispatcher.Main — Specific to Android usecase. This runs the required code on single UI thread &amp; should only be used for UI rendering. No heavy/blocking operation should be performed on this.</li></ol><h4>Examples to understand how Coroutines components work</h4><ol><li>Executing suspending functions sequentially</li></ol><pre>@Test<br>fun `executing suspending functions sequentially`() = runBlocking {<br>    val startTime = System.currentTimeMillis()<br>    dummyTask1()<br>    dummyTask2()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}</pre><blockquote>Just making a function suspend doesn’t do any magic (no parallelisation would be done on its own) &amp; both the function will take its own time &amp; execute sequentially &amp; total time taken would be 10secs</blockquote><p>Output will be</p><pre>Dummy task 1: 1<br>Dummy task 1: 2<br>Dummy task 1: 3<br>Dummy task 1: 4<br>Dummy task 1: 5<br>Dummy task 1 done<br>Dummy task 2: 1<br>Dummy task 2: 2<br>Dummy task 2: 3<br>Dummy task 2: 4<br>Dummy task 2: 5<br>Dummy task 2 done<br>Total time taken: 10 secs</pre><p>2. Executing suspending functions in parallel</p><pre>@Test<br>fun `executing suspending functions in parallel`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val startTime = System.currentTimeMillis()<br>    val job1 = scope.launch {<br>        dummyTask1()<br>    }<br>    val job2 = scope.launch {<br>        dummyTask2()<br>    }<br>    job1.join()<br>    job2.join()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}</pre><blockquote>At T = 0, code execution starts.<br>At lines <em>val job1</em> &amp;<em> val job2, </em>main code flow reaches at T = 0 itself &amp; 2 new coroutines are launched which starts executing separately, without blocking main code flow &amp; main code flow moves down</blockquote><blockquote>At T = 0 itself main code flow reaches at <em>job1.join()</em>. But now to move to next line from this, main code flow has to wait till <em>job1</em> is completed. As <em>job1</em> takes total of <em>5secs</em> to complete, so made code flow will reach line <em>job2.join()</em> at T = 5</blockquote><blockquote>At T = 5, again main code flow has to wait for <em>job2</em> to complete. But as <em>job2</em> had started executing in parallel at T = 0 itself, so at T = 5 <em>job2</em> is also completed. So main reaches end of the code at T = 5.</blockquote><blockquote>Note: Task1 &amp; Task2 gets executed in parallel and this specific order of 1 &amp; 2 is not guaranteed &amp; will keep changing everytime you re-run this code. Also completion order of both task might also defer every time you re-run this. The only thing guaranteed is both would be executing in parallel.</blockquote><p>Output will be</p><pre>Dummy task 1: 1<br>Dummy task 2: 1<br>Dummy task 2: 2<br>Dummy task 1: 2<br>Dummy task 2: 3<br>Dummy task 1: 3<br>Dummy task 1: 4<br>Dummy task 2: 4<br>Dummy task 2: 5<br>Dummy task 1: 5<br>Dummy task 2 done<br>Dummy task 1 done<br>Total time taken: 5 secs</pre><p>3. Executing suspending functions with return type in parallel</p><pre>@Test<br>fun `executing suspending functions with return type in parallel`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val startTime = System.currentTimeMillis()<br>    val job1 = scope.async {<br>        dummyTask3()<br>    }<br>    val job2 = scope.async {<br>        dummyTask4()<br>    }<br>    val sumTotal = job1.await() + job2.await()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>    println(&quot;Sum total: $sumTotal&quot;)<br>}<br><br>private suspend fun dummyTask3(): Int {<br>    var sum = 0<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 3: $i&quot;)<br>        delay(1000)<br>        sum += i<br>    }<br>    println(&quot;Dummy task 3 done&quot;)<br>    return sum<br>}<br><br>private suspend fun dummyTask4(): Int {<br>    var sum = 0<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 4: $i&quot;)<br>        delay(1000)<br>        sum += i<br>    }<br>    println(&quot;Dummy task 4 done&quot;)<br>    return sum<br>}</pre><blockquote>Similar to above example just with function having a return value</blockquote><p>Output will be</p><pre>Dummy task 3: 1<br>Dummy task 4: 1<br>Dummy task 3: 2<br>Dummy task 4: 2<br>Dummy task 4: 3<br>Dummy task 3: 3<br>Dummy task 4: 4<br>Dummy task 3: 4<br>Dummy task 3: 5<br>Dummy task 4: 5<br>Dummy task 3 done<br>Dummy task 4 done<br>Total time taken: 5 secs<br>Sum total: 30</pre><p>4. Completion of a job doesn’t wait by itself</p><pre>@Test<br>fun `completion of a job doesn&#39;t wait by itself`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val startTime = System.currentTimeMillis()<br>    scope.launch {<br>        dummyTask5()<br>    }<br><br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}<br><br>private suspend fun dummyTask5() {<br>    println(&quot;Starting dummy task 5&quot;)<br>    delay(5000)<br>    println(&quot;Dummy task 5 done&quot;)<br>}</pre><blockquote>Just because you have launched a coroutine, it doesn’t mean it will automatically wait for its completion before your main function is completed.</blockquote><p>Output will be</p><pre>Starting dummy task 5<br>Total time taken: 0 secs</pre><p>5. You have to ensure completion of a job</p><pre>@Test<br>fun `you have to ensure completion of a job`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val startTime = System.currentTimeMillis()<br>    val job = scope.launch {<br>        dummyTask5()<br>    }<br><br>    job.join()<br><br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}<br><br>private suspend fun dummyTask5() {<br>    println(&quot;Starting dummy task 5&quot;)<br>    delay(5000)<br>    println(&quot;Dummy task 5 done&quot;)<br>}</pre><blockquote>You need to ensure to have a <em>job.join() </em>for <em>launch</em> &amp; <em>job.await()</em> for <em>async</em> coroutines to be added before your main function completes.</blockquote><p>Output will be</p><pre>Starting dummy task 5<br>Dummy task 5 done<br>Total time taken: 5 secs</pre><p>6. Be careful where to wait for result from a suspending function</p><pre>@Test<br>fun `be careful where to wait for result from a suspending function`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br><br>    val startTime = System.currentTimeMillis()<br>    val job1 = scope.launch {<br>        dummyTask1()<br>    }<br>    job1.join()<br><br>    val job2 = scope.launch {<br>        dummyTask2()<br>    }<br>    job2.join()<br><br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}<br><br>private suspend fun dummyTask1() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 1: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 1 done&quot;)<br>}<br><br>private suspend fun dummyTask2() {<br>    for (i in 1..5) {<br>        println(&quot;Dummy task 2: $i&quot;)<br>        delay(1000)<br>    }<br>    println(&quot;Dummy task 2 done&quot;)<br>}</pre><blockquote>If you add <em>job.join(</em>) or <em>job.await()</em> as the case be, the main code flow execution will wait till the following job completes. If before waiting you have not started another task, then those tasks will not be executing in parallel</blockquote><p>Output will be</p><pre>Dummy task 1: 1<br>Dummy task 1: 2<br>Dummy task 1: 3<br>Dummy task 1: 4<br>Dummy task 1: 5<br>Dummy task 1 done<br>Dummy task 2: 1<br>Dummy task 2: 2<br>Dummy task 2: 3<br>Dummy task 2: 4<br>Dummy task 2: 5<br>Dummy task 2 done<br>Total time taken: 10 secs</pre><p>7. After how long will the function evaluation complete using launch</p><pre>@Test<br>fun `after how long will the function evaluation complete using launch`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val job1 = scope.launch {<br>        delay(5000)<br>        val endTime = System.currentTimeMillis()<br>        println(&quot;Task 1 completed at: ${(endTime - startTime) / 1000} secs&quot;)<br>    }<br><br>    val job2 = scope.launch {<br>        delay(3000)<br>        val endTime = System.currentTimeMillis()<br>        println(&quot;Task 2 completed at: ${(endTime - startTime) / 1000} secs&quot;)<br>    }<br>    job1.join()<br>    job2.join()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>At T = 0, main code flow will reach line <em>job1</em> &amp; launch separate coroutine to execute <em>job1</em></blockquote><blockquote>At T = 0, main code flow will reach line <em>job2</em> &amp; launch separate coroutine to execute <em>job2</em></blockquote><blockquote>At T = 0, main code flow will now wait for <em>job1</em> to complete</blockquote><blockquote>At T = 3, as <em>job2</em> had started executing in parallel, so it will finish &amp; print <em>Task 2 completed at 3 secs</em></blockquote><blockquote>At T = 5, <em>job1</em> would be finished, and output of <em>Task 1 completed at: 5 secs </em>would be displayed</blockquote><blockquote>At T = 5, main code flow will reach<em> job2.join()</em> and since <em>job2</em> is also completed it will continue moving and executing till end of the function</blockquote><p>Output will be</p><pre>Task 2 completed at: 3 secs<br>Task 1 completed at: 5 secs<br>Total time taken: 5 secs</pre><p>8. After how long will the function evaluation complete part 2 using launch</p><pre>@Test<br>fun `after how long will the function evaluation complete part 2 using launch`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val job1 = scope.launch {<br>        delay(5000)<br>        val endTime = System.currentTimeMillis()<br>        println(&quot;Task 1 completed at: ${(endTime - startTime) / 1000} secs&quot;)<br>    }<br><br>    val job2 = scope.launch {<br>        delay(3000)<br>        val endTime = System.currentTimeMillis()<br>        println(&quot;Task 2 completed at: ${(endTime - startTime) / 1000} secs&quot;)<br>    }<br>    job2.join()<br>    job1.join()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>Changing the order of join statements for both the job after its launched, wouldn’t impact the total time taken</blockquote><pre>Task 2 completed at: 3 secs<br>Task 1 completed at: 5 secs<br>Total time taken: 5 secs </pre><p>9. After how long will the function evaluation complete using async</p><pre>@Test<br>fun `after how long will the function evaluation complete using async`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val job1 = scope.async {<br>        delay(5000)<br>        val endTime = System.currentTimeMillis()<br>        &quot;Task 1 completed at: ${(endTime - startTime) / 1000} secs&quot;<br>    }<br><br>    val job2 = scope.async {<br>        delay(3000)<br>        val endTime = System.currentTimeMillis()<br>        &quot;Task 2 completed at: ${(endTime - startTime) / 1000} secs&quot;<br>    }<br>    println(job1.await())<br>    println(job2.await())<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>While this function overall will take the same amount of time.<br>But since we do print on<em> job1</em> 1st, so <em>job1</em> output will be displayed first followed by <em>job2</em></blockquote><blockquote>Do note that if we swap the println statement, “<em>Task 2 completed at”</em> would be displayed first followed by “<em>Task1 completed at”</em> &amp; the total time would remain the same</blockquote><p>Output will be</p><pre>Task 1 completed at: 5 secs<br>Task 2 completed at: 3 secs<br>Total time taken: 5 secs</pre><p>10. Time calculation for await all on async</p><pre>@Test<br>fun `time calculation for await all on async`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val jobList = mutableListOf&lt;Deferred&lt;Int&gt;&gt;()<br><br>    jobList.add(scope.async {<br>        delay(5000)<br>        1<br>    })<br><br>    jobList.add(scope.async {<br>        delay(9000)<br>        2<br>    })<br><br>    jobList.add(scope.async {<br>        delay(7000)<br>        3<br>    })<br><br>    val sum = jobList.awaitAll().sum()<br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Sum: $sum&quot;)<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>This is a very common usecase when we want to execute multiple independent functionalities in parallel &amp; at the end get results from all</blockquote><p>Output will be</p><pre>Sum: 6<br>Total time taken: 9 secs</pre><p>11. Predicting time when await will get executed</p><pre>@Test<br>fun `predicting time when await will get executed`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val job1 = scope.async {<br>        delay(5000)<br>        1<br>    }<br><br>    val job2 = scope.async {<br>        delay(9000)<br>        2<br>    }<br><br>    val job3 = scope.async {<br>        delay(7000)<br>        3<br>    }<br><br>    val job1Result = job1.await()<br>    println(&quot;Got job1Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br><br>    val job2Result = job2.await()<br>    println(&quot;Got job2Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br><br>    val job3Result = job3.await()<br>    println(&quot;Got job3Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br>    <br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>In this case, all the jobs will start in parallel (At T = 0)<br><em>job1</em> will complete at T = 5, <em>job3</em> will complete at T = 7 &amp; <em>job2</em> at T = 9<br>But the print statements would be based on the order of await.<br>When <em>.await()</em> is added, main code flow will stop at that point till that particular job is completed but the coroutines launched before will continue its execution</blockquote><p>Output will be</p><pre>Got job1Result after 5 secs<br>Got job2Result after 9 secs<br>Got job3Result after 9 secs<br>Total time taken: 9 secs</pre><p>12. Predicting time when await will get executed part 2</p><pre>@Test<br>fun `predicting time when await will get executed part 2`() = runBlocking {<br>    val scope = CoroutineScope(context = Job())<br>    val startTime = System.currentTimeMillis()<br><br>    val job1 = scope.async {<br>        delay(5000)<br>        1<br>    }<br><br>    val job2 = scope.async {<br>        delay(9000)<br>        2<br>    }<br><br>    val job3 = scope.async {<br>        delay(7000)<br>        3<br>    }<br><br>    val job2Result = job2.await()<br>    println(&quot;Got job2Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br><br>    val job3Result = job3.await()<br>    println(&quot;Got job3Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br><br>    val job1Result = job1.await()<br>    println(&quot;Got job1Result after ${(System.currentTimeMillis() - startTime) / 1000} secs&quot;)<br>    <br>    val endTime = System.currentTimeMillis()<br>    println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)<br>}</pre><blockquote>This case is similar to the one shared above just the order of .await statements are changed.<br>While the overall time taken will remain the same, the time for print statements will change</blockquote><p>Output will be</p><pre>Got job2Result after 9 secs<br>Got job3Result after 9 secs<br>Got job1Result after 9 secs<br>Total time taken: 9 secs</pre><p>13. How to optimise the total execution time</p><pre>@Test<br>fun `how to optimise the total execution time`() = runBlocking {<br><br>    val customerId = &quot;123&quot;<br><br>    val fetchFirstName: suspend (String) -&gt; String = { id -&gt;<br>        delay(5000)<br>        if (id == &quot;123&quot;) {<br>            &quot;FirstName&quot;<br>        } else {<br>            &quot;FirstName2&quot;<br>        }<br>    }<br><br>    val fetchMiddleName: suspend (String) -&gt; String = { id -&gt;<br>        delay(9000)<br>        if (id == &quot;123&quot;) {<br>            &quot;MiddleName&quot;<br>        } else {<br>            &quot;MiddleName2&quot;<br>        }<br>    }<br><br>    val fetchLastName: suspend (String) -&gt; String = { id -&gt;<br>        delay(7000)<br>        if (id == &quot;123&quot;) {<br>            &quot;LastName&quot;<br>        } else {<br>            &quot;LastName2&quot;<br>        }<br>    }<br><br>    val fetchContactNumber: suspend (String) -&gt; String = { id -&gt;<br>        delay(3000)<br>        if (id == &quot;123&quot;) {<br>            &quot;ContactNumber&quot;<br>        } else {<br>            &quot;ContactNumber2&quot;<br>        }<br>    }<br><br>    val finalName: suspend (String, String, String) -&gt; String =<br>        { firstName, middleName, lastName -&gt;<br>            delay(3000)<br>            &quot;Mrs. $firstName $middleName $lastName&quot;<br>        }<br>}</pre><blockquote>Imagine a scenario where you have customerId<br>And to get firstName, middleName &amp; lastName you need to make some API/DB call and the parameter needed is customerId<br>To get contactNumber you need a API/DB call for that as well you just need customerId<br>To get finalName you need to make another API/DB call but you need to paas firstName, middleName &amp; lastName as parameter. [Probably a very bad design]<br>What would be the most optimised way for this ?</blockquote><p>Code for most optimised solution</p><pre>val startTime = System.currentTimeMillis()<br><br>val nameFetchDeferredList = mutableListOf&lt;Deferred&lt;String&gt;&gt;()<br>nameFetchDeferredList.add(async { fetchFirstName(customerId) })<br>nameFetchDeferredList.add(async { fetchMiddleName(customerId) })<br>nameFetchDeferredList.add(async { fetchLastName(customerId) })<br><br>val contactNumberDeferred = async { fetchContactNumber(customerId) }<br><br>// At this point, all the above tasks are running in parallel<br><br>val finalNameDeferred = async {<br>    val nameList = nameFetchDeferredList.awaitAll()<br>    finalName(nameList[0], nameList[1], nameList[2])<br>}<br><br>val finalNameResult = finalNameDeferred.await()<br>val contactNumberResult = contactNumberDeferred.await()<br><br>val endTime = System.currentTimeMillis()<br>println(&quot;Total time taken: ${(endTime - startTime) / 1000} secs&quot;)</pre><p>Answer would be — 12 secs</p><p>Thank you for reading till the end. Hope you now have a good understanding on fundamentals of coroutine &amp; how to use it. <br>To increase your skill set to another level, hop on to<a href="https://medium.com/@ujjwalkr.maharana/all-about-kotlin-coroutines-series-part-2-ee0d22205c82?source=friends_link&amp;sk=84e7e550600921d3adf0883b7ce883d0"> Part 2 of this series</a>. Part 2 deals with exception handling &amp; cancellation and how suspend function works under the hood.</p><p>Thank you for reading. Any feedback / questions are welcomed. You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01d5510fdf3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WhiteHat Jr — A scam or a revolution?]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/whitehat-jr-a-scam-or-a-revolution-497cb4745cbc?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/497cb4745cbc</guid>
            <category><![CDATA[whitehat]]></category>
            <category><![CDATA[whitehat-jr]]></category>
            <category><![CDATA[whitehatjr-reviews]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 13:09:50 GMT</pubDate>
            <atom:updated>2020-10-18T13:09:50.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>WhiteHat Jr — A scam or a revolution?</h3><p>[Perspective of a software engineer]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Yz47MvC_axoGIWxL21RKzA.jpeg" /><figcaption>WhiteHatJr</figcaption></figure><p>There isin’t any problem with the idea of teaching coding to kids but the problem lies with the claims and way of selling this idea. The subtle way of enforcing the idea to Indian parents that you need to focus on teaching coding to your kids so that they can earn in crores is the main issue.</p><p>In a society like us, where a majority of family struggles with income sources, societal norms are given the utmost priority, and what others will think or say is always taken into consideration. And to add to this, one parenting attribute which is present around us is using children’s success to showoff to society. With all these factors, the journey of a majority of student is guided not by choice or passion but by these external factors. In the movie ‘Shubh Mangal Zyada Saavdhan’, to the incident where Aman Tripathi (Jitendra Kumar) confesses to his father that he is gay, Katik Singh (Ayushmaan Khurana) says that the father will get tensed and anxious not because of what his child had to go through all these years but rather what will society think and react to this. Basically, our society moves by not what internal thought process, capabilities, needs, and aspirations but rather how and what is considered to be “normal” by the external surrounding.</p><p>Perfectly understanding the functioning of our society, the company is leveraging this in their advertisement wherein a neighbour gets shocked when the kids parent tells him that their son made an app for which all investors are fighting to invest.</p><p>An argument could be made that why we shouldn’t do it. Kids will learn to code, it is in demand, and many opportunities will open up for them.</p><p>The issue here isn’t about the opportunity, especially considering the age group they are targeting. If a kid learns something out of her/his interest, its perfectly normal and should be promoted. But with these kinds of marketing, it’ll indirectly force parents to compulsorily make their kids learn coding so that the parents continue to showoff in the external environment. In this the consent, the interest and the passion of kids will slowly subside. In an age group where the kids must have the freedom to learn by choice, have space to slowly develop their own thinking and logical ability, they would be bounded by the pressure to learn something which they even may not be interested.</p><p>In a society where already we are facing innovation crisis and out of box thinkers, the mindset that after 12th you either enrol in engineering or opt for medical while other streams are “inferior”. Another mindset setback like this would endanger our society even more.</p><p>Coming to the point of making them ready for the opportunities available. If they are really concerned about this, shouldn’t then they be teaching this to college students who would be entering professional careers. According to a study by employability assessment company Aspiring Minds in 2017, 95% engineers in India are unfit for software development jobs. In a test conducted among 36000 engineering students from IT related branches of over 500 colleges over 2/3 could not even write code that compiles. The study further noted that only 1.4 per cent can write functionally correct and efficient code. Moreover, programming skills are five times poorer for tier III colleges as compared to tier 1 colleges. “Sixty nine per cent of candidates from top 100 colleges are able to write a compilable code versus rest of the colleges where only 31 per cent are able to write a compilable code,” the report said.</p><p>If this is the industrial scenario, are they actually solving the problem of the society which is what all startups intend to do, by taking this platform to school kids. Or are they just another money-making organisation aimed at targeting the weakness of our society.</p><p>I myself am a software engineer placed in a well reputed firm. Currently, I work in “cool” domain of data science and machine learning. I have studied from Tier-1 engineering college in India. I have been through all of this. And after all this what I observed is the coding is just a tool to help us solve real-world problems.<br><br> I developed a deep learning model for detection of aircrafts -&gt;aimed at automatic identification of aircrafts for security purpose. <br>I created a ML model for lead score prediction -&gt;purpose was to prioritise genuine customers and hence ease the process of reach out team.<br>I worked on mobile data analysis -&gt; purpose was to generate a psuedo credit score for customers not eligible for bureau scores.<br>All the coding knowledge and skills were aimed at a bigger thing: solving real-world problems.</p><p>Coding is an important skill to have in the modern world but shouldn’t be hyped as to start learning from class-1. I personally know many who had no knowledge of coding before college, they started learning during college using open source contents and now is as skilled as anyone else. If this is the case, then why spend thousands, force kids and make them learn something which when required they can learn on their own free of cost. Coding is a skill, not a fundamental, and skills can be acquired easily in a short duration of time. Kids need to have their own space of learning, wherein they focus on fundamentals first, inculcate values of discipline, moral values, ethics and more importantly develop the ability of thinking and identifying problems. Solving them can be learnt later.</p><p>Any feedback or constructive criticism is welcomed. You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=497cb4745cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remembering Direct Action Day, The 1946 Calcutta killings]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/remembering-direct-action-day-the-1946-calcutta-killings-cd1beb1d6508?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1beb1d6508</guid>
            <category><![CDATA[16-august-1946]]></category>
            <category><![CDATA[1946-calcutta-killings]]></category>
            <category><![CDATA[crux-of-indias-partition]]></category>
            <category><![CDATA[1946-cabinet-mission]]></category>
            <category><![CDATA[direct-action-day]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 09:48:00 GMT</pubDate>
            <atom:updated>2020-08-16T11:22:36.791Z</atom:updated>
            <content:encoded><![CDATA[<p>[The crux of partition of India]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*tEKGGdJTOtDVBDAKMO3Q7g.png" /></figure><p>“<em>Maar ke lenge Pakistan, lad ke lenge Pakistan, le kar rahenge Pakistan, Allahu Akhbar, nara-i-takhbir</em>”<em> </em>(We will kill and fight to create Pakistan, we are determined to create Pakistan.) This was the slogan that echoed in the streets of Bengal on the afternoon of August 16, 1946.</p><p>The 1946 cabinet mission came to India aimed to discuss the transfer of powers from the British government to the Indian leadership. The major parties involved in the discussions were the Indian National Congress, All India Muslim League and representatives from different provincial states. While Indian National Congress demanded a unified India, Mohammad Ali Jinnah wanted a separate state to safe guard the interest of Muslims as he feared that in a Hindu dominated government the minorities voices and demands would be suppressed. On 16th May 1946, the cabinet proposed a plan of composition of the new Dominion of India and its government. Muslim League’s demand was catered by creating a new tier of ‘groups of provinces’ in northwest and the east wherein the central government was expected to handle the subjects of defence, external affairs and communications while all other powers would be relegated to the ‘groups’.</p><p>With the failure of the cabinet to get both sides agreeing to a common solution, Jinnah announced 16 August 1946 would be “Direct Action Day” and warned Congress, “We do not want war. If you want war we accept your offer unhesitatingly. We will either have a divided India or a destroyed India.” The Communist Party extended its full support to the Pakistan Movement. The maiden meeting of the Muslim League that was held in the Ochterlony Monument Ground in Calcutta on the Direct Action Day of 16 August 1946 resounded with inflammatory anti-Hindu sloganeering and speeches. The meeting was attended by Jyoti Basu, Leader of the CPI in Bengal Legislative Assembly and two other communist MLAs. The League Chief Minister of Bengal, H S Suhrawardy declared a holiday in the State with the obvious intent of facilitating the bandh and ordered entire police department to go on holiday. The call from Jinnah, the police on holiday and the army waiting in their barracks with their dragon tanks, Bengal witnessed the mayhem in the name of Muslim separatism. The protagonists of Pakistan pounced upon the Hindu citizens as they were presumed to be the votaries of undivided India.</p><p>Devendra Panigrahi, in his seminal <em>India’s Partition: The Story of Imperialism in Retreat,</em> quotes the 13 August 1946 issue of Muslim league mouthpiece <em>The Star of India</em>, which gave detailed instructions on how to observe ‘Direct Action Day’. The newspaper wrote: “<em>Muslims must remember that it was in Ramzan that permission for jehad was granted by Allah. It was in Ramzan that the Battle of Badr, the first open conflict between Islam and heathens, was fought and won by 313 Muslims and again it was in Ramzan that 10,000 Muslims under the Holy Prophet conquered Mecca and established the Kingdom of Heaven and the commonwealth of Islam in Arabia. The Muslim League is fortunate that it is starting its action on this Holy month and day”</em></p><p>Suhrawardy wanted to ensure that the Hindus of Calcutta and its neighboring districts do not start opposing the integration of areas in Bengal into Pakistan as the Hindus were in majority. For this reason, the Hindus had to be terrorised and beaten into submission. Suhrawardy realised that without Calcutta and its industrially and economically advanced surrounding areas like Howrah and Hooghly (where also Hindus were in a majority), East Pakistan would be economically hobbled and so it was very important to have all these areas into East Pakistan. Suhrawardy’s personal diaries reveal he was an Islamist hardliner who believed in making the entire Indian sub-continent an Islamic state.</p><p>With the lead from Jinnah, incite from Suhrawardy, more than 4,000 people lost their lives and 100,000 residents were left homeless in Calcutta within 72 hours. The riots involved killing, rape, forced conversions and looting. This violence sparked off further religious riots in the surrounding regions of Noakhali, Bihar, United Provinces (modern UP), Punjab, and the North West Frontier Province. The worst riots, however, were reported from Noakhali. All this bloodshed and communal tensions ultimately led to the INC’s acceptance of the partition of the country in order to suppress the violence and blood bath.</p><p>After days of mayhem, Bengal was put under Viceroy’s rule on 21 August, five battalions of British troops supported by four battalions of Indian and Gurkha troops were deployed in Calcutta. Rioting and violence eventually stopped. The 16th of August will remain a black day in Indian history and the supreme sacrifice made by the votaries of undivided India should be gratefully remembered.</p><p>Any feedback or constructive criticism is welcomed. You can find me either on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1beb1d6508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Story of 1975 Emergency]]></title>
            <link>https://medium.com/@ujjwalkr.maharana/the-story-of-1975-emergency-80b220360b85?source=rss-ec0ea33d24c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/80b220360b85</guid>
            <category><![CDATA[emergency-1975]]></category>
            <category><![CDATA[emergency-in-india]]></category>
            <category><![CDATA[fall-of-congress]]></category>
            <category><![CDATA[indira-gandhi]]></category>
            <category><![CDATA[india]]></category>
            <dc:creator><![CDATA[Ujjwal Kumar Maharana]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 10:01:01 GMT</pubDate>
            <atom:updated>2020-06-26T10:01:01.503Z</atom:updated>
            <content:encoded><![CDATA[<p>[A demise of democracy or a festival of discipline]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*JEI-NKsl7K3fGSFB5fD1Tw.jpeg" /></figure><p>Various factors led to the declaration of emergency, and the most immediate was a judicial decree. Raj Narain, a socialist who was recently defeated by Indira Gandhi in the Rae Bareilly parliamentary constituency of Uttar Pradesh, submitted to the Allahabad High Court charges of corruption in the election process against Mrs. Gandhi. On June 12th, 1975, Justice Jagmohan Lal Sinha of the Allahabad High Court, found the Prime Minister guilty on the charge of misuse of government machinery for her election campaign. The court declared her election “<em>null and void</em>” and unseated her from the Lok Sabha. The court also banned her from contesting in any election for an additional six years. Justice Sinha stayed the operation of his judgment for 20 days allowing the Congress party to elect a successor to the Prime Minister. Unable to find a competent successor, Mrs Gandhi, on June 23rd 1975 appealed for “<em>complete and absolute</em>” stay to the Supreme Court which would have permitted her to be a voting Member of Parliament, as well as Prime Minister. On June 24th 1975 Justice Iyer granted Indira Gandhi “<em>conditional stay</em>”. This decision gave rise to outcries from the opposition that she should resign. Mrs Gandhi did not resign.</p><p>Prior to this the social and economic condition of the country was in bad shape. Although the win over Pakistan in the war brought much praise for Indira Gandhi from the common man, the war and the eight million refugees from Bangladesh had put a heavy strain on our economy. A persistently high level of inflation was causing great distress to the people. Moreover, industrial growth was low, and unemployment was high. The protests in Gujarat and Bihar, led by students, played a pivotal role in galvanising a nationwide opinion against Congress and the Prime Minister. Subsequently, elections were held in Gujarat in June 1975, which the Congress lost. Students in Bihar came together in march 1974 to protest against rising prices, food scarcity, unemployment and corruption. As the movement gained strength, they invited Jayaprakash Narayan (JP), who had given up active politics and was involved in social work, to lead it. He accepted it and took the movement to the national level. JP led a massive political rally in Delhi’s Ramlila grounds on 25th June 1975, where he announced a nationwide Satyagraha for Indira Gandhi’s resignation and asked the army, police and government employees not to obey ‘illegal and immoral orders’. Around 5 lakh people attended that rally.</p><p>As her government had been invalidated, Gandhi had little legitimate recourse. Thus, she turned to the permissive Indian constitution — Article 352. “<em>If the President is satisfied that a grave Emergency exists whereby the security of India or of any part of the territory thereof is threatened, whether by war or external aggression or internal disturbance, he may, by proclamation, make a declaration to that effect</em>.” The friendly President obliged. Gandhi persuaded President Fakhruddin Ali Ahmed to declare a national state of emergency, which empowered her to do whatever she considered “<em>best</em>” for the country for at least six months. In the short term, this meant political suppression and pacification of the growing opposition.</p><p>After 25th midnight, the electricity to all the major newspaper offices was disconnected and was restored only two to three days later after the censorship apparatus had been set up. Sanjay Gandhi, son of Indira Gandhi, asked the information and broadcast minister Mr Inder Kumar Gujral that from henceforth the news broadcasted on radio and doordarshan would first be read by him before being aired. To this Mr Gujral clearly opposed, stating that news is a secret document and no one is allowed to see it before being aired. Mrs Gandhi came at that moment and asked the minister to keep an officer along with him who would bring news to PM’s office before it is being broadcasted. Soon after the ministry of Mr Gujral was changed. This story was narrated by Mr Gujral himself few years later and he clearly said that although Indira Gandhi was the PM the real power was taken over by her son Sanjay Gandhi who was not even a member of parliament.</p><p>Early morning, on 26th, a large number of opposition leaders and workers were arrested. The Union Cabinet was only informed about it at a special meeting at 6 a.m after all this was over. The government made blatant and extensive use of its power of preventive detention. People were arrested and detained only on the apprehension that they may commit an offense. At around 2 p.m of 26th June even before announcing the emergency to public, Mr JP was arrested from Gandhi place foundation. Nearly 1,11,000 people was arrested along with 13,000 opposition leaders. All the fundamental rights were null and void for them. Sanjay Gandhi, the Prime Minister’s younger son, gained control over the administration and allegedly interfered in the functioning of the government.</p><p>On October 27, 1975 TIME Magazine article pointed out: “<em>…political debate in India has been effectively silenced. Newspapers have become dull and predictable, and people seem reticent about discussing controversial matters in public. From the beginning of the Emergency, much of the government’s anger has been directed at the press.</em>” Article 21 — protection of life and personal liberty was taken away. Putting someone in prison or shooting someone henceforth couldn’t be questioned. No trial was to be conducted for people who were put in prison. In September 1976, Sanjay Gandhi initiated a widespread compulsory sterilisation programme to limit population growth.</p><p>Before the emergency there were numerous occasion when Supreme court had overturned the bills passed by Mrs Gandhi’s government. Prior to this government couldn’t make any such amendments which would change the core value and fundamental rights in the constitution. Golaknath vs. State Of Punjab or simply the Golaknath case, in 1967, Court ruled that Parliament could not curtail any of the Fundamental Rights in the Constitution. With the judiciary keeping a continuous check on the unlimited power of the government, Indira Gandhi’s government brought the 24th amendment act, which now enabled Parliament to dilute Fundamental Rights through Amendments of the Constitution. It also amended article 368 to provide expressly that Parliament has power to amend any provision of the Constitution. Before this government wanted to bring all private bank under government control, this was passed by the parliament but the supreme court again overturned this. And thus, the government brought the 25th amendment act, which would permit any private property acquisition by the government on payment of compensation which would be decided by the parliament and not the court. The amendment also exempted any law giving effect to the article 39(b) and (c) of Directive Principles of State Policy from judicial review, even if it violated the Fundamental Rights. She also took away from the apex court the authority to adjudicate election disputes relating to the president, the vice-president, the prime minister and the Lok Sabha speaker and transferred it to a body to be appointed by Parliament.</p><p>With judiciary not complying with unlimited power of government, after the retirement of Chief Justice of India Sarv Mittra Sikri as per the tradition next justice seniority wise was to be appointed as CJI but the government made Justice A. N. Ray, superseding 3 senior Judges before him. All 3 senior judges later resigned. Mr JP wrote an open letter to all the members of parliament mentioning how government is making judiciary a show of their hand and that this would later come back and harm our own country.</p><p>After an 18-month stint, Indira Gandhi ended Emergency rule by announcing general elections for the Lok Sabha. Accordingly, all the leaders and activists were released from jails. Although this gave the opposition very little time, it quickly united to form a new party, Janata Party, under the leadership of Mr JP. For the first time since independence, the Congress party was defeated in the Lok Sabha elections. The Congress could win only 154 seats in the Lok Sabha, whereas the Janata Party got 295 seats (330, along with its allies). Indira Gandhi was defeated from Rae Bareli, as was her son Sanjay Gandhi from Amethi.</p><p>The Emergency was endorsed by Vinoba Bhave (who called it Anushasan Parva or Time for discipline). Pioneer industrialist J.R.D Tata, and writer Khushwant Singh were among the other prominent supporters. Some have argued that India badly needed economic recovery after the Indo-Pak war had strained the exchequer. Indira’s 20-point economic program increased agricultural production, manufacturing activity, exports and foreign reserves. The national economy achieved high levels of growth and investment, and as strikes were non-existent, productivity increased rapidly. Communal Hindu-Muslim riots, which had resurfaced in the 1960s, and 70s, virtually ceased, and initially, the government seemed to be working with vigour. Police in cities had sweeping powers to destroy gang and syndicate structure.</p><p>Was the emergency a demise of democracy or a festival of discipline? This was and will remain a subjective evaluation based on the perspective from which we see. But one thing is for sure that this will always remain a major event of Indian politics because for the first time after Independence India saw a change of power at the center and the start of an era where people went from having mono-political party system to a somewhat open market political party system.</p><p>Any feedback or constructive criticism is welcomed. You can either find me on Twitter <a href="https://twitter.com/MaharanaUjjwal"><em>@MaharanaUjjwal</em></a> or on LinkedIn <a href="https://www.linkedin.com/in/ujjwalmaharana/"><em>@UjjwalMaharana</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80b220360b85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>