<?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[Hamropatro - Medium]]></title>
        <description><![CDATA[Maker of most popular Nepali Apps including Hamro Patro (5M+ Downloads) and Hamro Nepali Keyboard ( 5M+ Downloads) - Medium]]></description>
        <link>https://medium.com/smartideas?source=rss----7e6736c27dd3---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Hamropatro - Medium</title>
            <link>https://medium.com/smartideas?source=rss----7e6736c27dd3---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:46:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/smartideas" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Coexisting with Coroutines — 1]]></title>
            <link>https://medium.com/smartideas/coexisting-with-coroutines-1-cf7d5e8500d8?source=rss----7e6736c27dd3---4</link>
            <guid isPermaLink="false">https://medium.com/p/cf7d5e8500d8</guid>
            <category><![CDATA[async-functions]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ayush Shakya]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 06:45:53 GMT</pubDate>
            <atom:updated>2020-02-07T02:12:42.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coexisting with Coroutines — 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLZ-aLaji3JlLy9CY3_1Gw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@felixmittermeier"><strong>Inactive.</strong></a> from <a href="https://www.pexels.com/photo/person-about-to-catch-four-dices-1111597/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a></figcaption></figure><p>Multithreading is a important skill in the arsenal of any seasoned programmer which if used correctly, can enable a seamless experience, keeping the main thread as free as possible and shielding the user from the lag introduced by long running operations. Over the years, this technique has seen many incarnations in the Android framework : beginning with Thread and AsyncTask to more modern standards such as ReactiveX, Jobs and the topic of interest for this article : Kotlin Coroutines.</p><p>Coroutines are an interesting new mechanic in Kotlin that allows us to approach multithreading in a novel way, granting us the ability to write more “sequential” code that is easier to digest and build. Utilizing the various constructs in coroutines, we can easily deal with complex concurrency demands of a modern app architecture and at the same time circumvent the dreaded callback hell that is so notoriously associated with traditional asynchronous programming.</p><p>To uncover the inner mechanisms of coroutines, it is very important understand the difference between blocked and suspended functions. To grasp this difference and what they represent, consider the trivial usecase of displaying text after a brief delay:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec14a9ad455a0340cf21d557d2b7c22/href">https://medium.com/media/8ec14a9ad455a0340cf21d557d2b7c22/href</a></iframe><p>This is a example of a blocked process. The current thread is blocked for a certain period(5 seconds) and after which the remaining piece of text is logged.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7abd5e8f19ddcb6fedc2ffdd75fc61a/href">https://medium.com/media/c7abd5e8f19ddcb6fedc2ffdd75fc61a/href</a></iframe><p>This is the suspending version of the same usecase. Ignore the fancy new nomenclature such as <em>GlobalScope</em>/<em>launch</em>/<em>delay</em>/<em>suspend </em>for now and pay close attention to the order of the log statements. Even though the order has been reversed, the output is same as the blocking version. Lets dive into how this is possible.</p><h4>Suspend vs. Block.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FC6JQPEUsZUyVq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FC6JQPEUsZUyVq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FC6JQPEUsZUyVq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e614410b4e3f6fb32a3dd6978d30033/href">https://medium.com/media/6e614410b4e3f6fb32a3dd6978d30033/href</a></iframe><p>To give a super low level definition, suspending and blocking functions both create processes whose execution has been halted but the reason for this halt is different for each. Blocked processes exist because they required a external resource that is yet not available. Suspended processes on the other hand, exist because the OS has preemptively decided to stop their execution. This implies that they can be resumed at any time as they do not depend on any external resources.</p><blockquote>Blocked processes exist because they required a external resource that is yet not available. Suspended processes on the other hand, exist because the OS has preemptively decided to stop their execution. This implies that they can be resumed at any time as they do not depend on any external resources.</blockquote><p>At a language level, functions that execute one after the other maybe considered examples of blocked processes. The second functions is blocked as the first function is still running. A normal function thus corresponds to a blocked process and as a consequence for the sake of clarity, suspend functions are prefixed with the ‘suspend’ keyword before the function.</p><pre>suspend fun functionName(){/*function body*/}</pre><p>The keyword serves a much larger purpose than simply being a qualifier however. If a function is prefixed the ‘suspend’ keyword, it is declaring that it may require some time complete its task. Keeping this in mind, lets look at the simple program below.</p><pre>fun main() {test()}</pre><pre>suspend fun test(){<br>    <em>delay</em>(1000L)<br>    <em>println</em>(&quot;World!&quot;)<br>}</pre><p>Pointing out the obvious: this will throw a compilation error declaring that suspend functions can only be called from other suspend functions or a coroutine. Why is that? To answer this question, lets talk about two new concepts : <strong>CoroutineScopes</strong> and <strong>CoroutineBuilders</strong></p><h4><strong>CoroutineScopes</strong></h4><blockquote>Coroutines can be seen as subtasks meant to be executed without blocking a thread.</blockquote><p>Coroutines can be seen as subtasks meant to be executed without blocking a thread. Due to this reason, we need some way to control their lifecycle incase they overstay their welcome. For instance, consider a app with a screen which initiates a network call to display the result in a list it contains. Along with this list there is also a button that routes to a second screen. If the user chooses to navigate to the second screen at any point during which a network call is in progress, the call should be cancelled entirely. To accomplish this, we need some help to control the lifecycle of the coroutine and this help comes in form of a <strong>CoroutineScope</strong>.</p><pre>lateinit var coroutineScope : CoroutineScope</pre><blockquote>GlobalScope as used in suspended process example above, is a implementation of a CoroutineScope that keeps the coroutine alive until the application is destroyed.</blockquote><p>With a reference to a coroutineScope, we can cancel any coroutine called inside this scope through the extension function :</p><pre>coroutineScope.cancel()</pre><p>Lets revisit our network call example and see how we can enhance it with <strong>CoroutineScopes</strong>.</p><pre>gotoNextScreenbtn.setOnClickListener <strong>{</strong>coroutineScope.<em>cancel</em>()<strong>}<br><br></strong>coroutineScope.<em>launch </em><strong>{<br>    </strong>//block network<br>    showProgress()<br>    someNetworkCall()<br>    dismissProgress()<br>    //block network<br><strong>}</strong></pre><p>From the piece of code above, we can see that even while a network call is in progress, we can call <em>coroutineScope.cancel() </em>to cancel the coroutine(i.e block network) in that scope and the call as a result<em>. </em>The ability to cancel a network call midway is fine and all but what does launch signify? Well, <em>launch </em>is another extension function of a <strong>CoroutineScope </strong>that is an example of a <strong>CoroutineBuilder</strong>.</p><h4>CoroutineBuilders</h4><p><strong>CoroutineBuilders </strong>are the ones actually responsible for running the coroutine. Depending on the type of builder used, a coroutine can be made to execute differently.</p><p>If we are not dependent on the result of the coroutine and simply want it to execute in the background while we perform some other tasks, <em>launch </em>is the perfect choice. Due to this reason, it is commonly used to launch a parent coroutines that house multiple coroutines. In our preceeding example,<em> launch </em>houses <em>someNetworkCall()</em><strong> </strong>which is actually another coroutine which runs using another commonly used builder : <em>async</em></p><p><em>async </em>unlike <em>launch </em>is used when we are dependent on the result of a coroutine and are required to wait for it. A possible implementation of <em>someNetworkCall()</em><strong> </strong>could be the following</p><pre>private suspend fun someNetworkCall() = coroutineScope.<em>async </em><strong>{<br>    </strong>//some long running network call<br>    &quot;result of that call&quot;<br><strong>}</strong>.await()</pre><p><em>await()</em> is a suspending function used in tandem with <em>async()</em> that executes the coroutine in the background and returns the result.(Note that since <em>await() </em>is suspending, <em>someNetworkCall </em>is also suspending). It is perfect for executing network calls where we require the response to continue. In our network call example, <em>someNetworkCall() </em>runs first and after it returns a result, only then <em>dismissProgress() </em>is executed.</p><p>By now it should be abundantly clear, why a coroutine is used to execute suspending functions. It provides a safe place to call these special functions through the support of <strong>CoroutineScopes</strong> and <strong>CoroutineBuilders</strong>. So where do these coroutines actually run? Since suspend functions take time to complete execution, a coroutineScope usually references thread(s) to execute them. These references come in form of <strong>Dispatchers.</strong></p><h4><strong>Dispatchers</strong></h4><p>Dispatchers represent the thread(s) in which the coroutine is set to execute. The 3 widely used dispatchers include</p><ul><li>Dispatchers.Main which represents the UI thread in Android.</li><li>Dispatchers.IO which handles I/O and network operations</li><li>Dispatchers.Default which is suited for handling long processing operations such as stream or image processing.</li></ul><h4>Putting It All Together</h4><p>Now that the basics have been put forward, lets solidify our concept of coroutines with a kind of all-inclusive example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46fa673798fddf247edbb9721140556a/href">https://medium.com/media/46fa673798fddf247edbb9721140556a/href</a></iframe><p>This example demonstrates two things : how many of the previously discussed basic coroutine core features interact with each other, and the effect of nested coroutines. If you observe the example you can see 3 levels of nesting :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7279e95c93e8deb9a2a55a031909007/href">https://medium.com/media/c7279e95c93e8deb9a2a55a031909007/href</a></iframe><p>Note that when the innermost coroutineBuilder : <em>async()</em> executes calling its corresponding <em>await()</em>, only its enclosing coroutine is suspended.(i.e <em>Block </em>inner). The outermost coroutine (i.e <em>Block outer</em>) is still running as demonstrated by the log statement. Lets recall a portion of distinction between blocked and suspended processes :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQYSgo7te5uhhZjz155%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQYSgo7te5uhhZjz155%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQYSgo7te5uhhZjz155%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce52a781564a5266a1f909b301d7774/href">https://medium.com/media/0ce52a781564a5266a1f909b301d7774/href</a></iframe><blockquote>……Suspended processes on the other hand, exist because the OS has preemptively decided to stop their execution. This implies that they can be resumed at any time as they do not depend on any external resources.</blockquote><p>Because <em>await() </em>suspended(<em>preemptively decided to stop their execution</em>) the innermost coroutine, the current thread is free to continue execution with the outermost coroutine until <em>await()</em> returns with a result(<em>can be resumed at any time</em>).</p><h4><strong>Adios…for now</strong></h4><p>Obviously, this article provides a very high level introduction to coroutines which can a difficult subject for beginners to wrap around their heads. There’s alot more going on under the hood with coroutines and definitely plan to expand on them in future articles. But for now I hope that this article has managed to teach you the core of coroutines in a intuitive way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf7d5e8500d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/smartideas/coexisting-with-coroutines-1-cf7d5e8500d8">Coexisting with Coroutines — 1</a> was originally published in <a href="https://medium.com/smartideas">Hamropatro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>