<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pritam Kadam</title>
    <description>The latest articles on DEV Community by Pritam Kadam (@_pritam_kadam_).</description>
    <link>https://dev.to/_pritam_kadam_</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F256830%2F6808d24c-fcb8-424e-98dd-22f17d41feb6.jpg</url>
      <title>DEV Community: Pritam Kadam</title>
      <link>https://dev.to/_pritam_kadam_</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/_pritam_kadam_"/>
    <language>en</language>
    <item>
      <title>Everything you need to know about kotlin coroutines</title>
      <dc:creator>Pritam Kadam</dc:creator>
      <pubDate>Wed, 30 Oct 2019 10:24:26 +0000</pubDate>
      <link>https://dev.to/_pritam_kadam_/everything-you-need-to-know-about-kotlin-coroutines-4bfg</link>
      <guid>https://dev.to/_pritam_kadam_/everything-you-need-to-know-about-kotlin-coroutines-4bfg</guid>
      <description>&lt;h1&gt;
  
  
  Everything you need to know about kotlin coroutines
&lt;/h1&gt;

&lt;p&gt;My agenda for this blog post is to get yourself familiar with different terminologies of coroutines and answer the following questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Difference between &lt;strong&gt;&lt;em&gt;Job&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;Deferred&lt;/em&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;em&gt;launch&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;async&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Which &lt;strong&gt;&lt;em&gt;coroutine builder&lt;/em&gt;&lt;/strong&gt; you should use?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What happens when a &lt;strong&gt;&lt;em&gt;exception&lt;/em&gt;&lt;/strong&gt; is thrown in coroutine?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;At a very high level, how &lt;strong&gt;&lt;em&gt;structured concurrency&lt;/em&gt;&lt;/strong&gt; is achieved?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A thread-safe shared mutable state with a &lt;strong&gt;&lt;em&gt;single-threaded dispatcher&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;IO&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;CPU&lt;/em&gt;&lt;/strong&gt; bound operations with coroutines&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To understand how coroutines work and use them effectively in real-world applications, you need to first understand its core concepts.&lt;/p&gt;

&lt;p&gt;We are going to cover the following topics in the rest of the write-up:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Coroutine Scope Builders&lt;/strong&gt; (MainScope, CoroutineScope, coroutineScope, GlobalScope, etc.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;CoroutineContext&lt;/strong&gt; (Job, Deferred, etc.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Coroutine Builders&lt;/strong&gt; (launch, async, withContext, runBlocking, etc.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Structured concurrency&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Suspend&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Continuation&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Coroutine" rel="noopener noreferrer"&gt;Coroutines&lt;/a&gt; are light-weight threads and the construction of coroutine is very cheap. They do not directly map to native os threads, because of that they are very faster to create and destroy compared to threads. There is no additional overhead of switching context between threads. Practically you can have thousands of or even tens of thousands of coroutines. There might be only one thread having thousands of coroutines.&lt;/p&gt;

&lt;p&gt;The two most important building blocks to create/start/run new coroutines are &lt;strong&gt;coroutine scope&lt;/strong&gt; and &lt;strong&gt;coroutine builders&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Coroutine scope consists of all the machinery required to run coroutine, for example, it knows where (on which thread) to run coroutine and coroutine builders are used to create a new coroutine.&lt;/p&gt;

&lt;p&gt;If I have to give an analogy with threads, coroutine scope can be seen as Java’s &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html" rel="noopener noreferrer"&gt;ExecutorService&lt;/a&gt; and coroutine builders are factories to create &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html" rel="noopener noreferrer"&gt;Runnable &lt;/a&gt;instances.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;CoroutineScope is more than just &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html" rel="noopener noreferrer"&gt;ExecutorService&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To demonstrate that coroutines are &lt;strong&gt;&lt;em&gt;light-weight&lt;/em&gt;&lt;/strong&gt;, let’s look at the following examples where we create 100 thousand coroutines vs 100 thousand threads and print(".") in each one of them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;100_000 coroutines:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/OBD3iKVmpH?from=4"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The above application does not crash and prints 100_000 dots.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; Do not worry about launch and runBlocking used in the above example, this is explained in detail in later sections of this article. Just know that runBlocking creates coroutine scope which can be seen as setting up an environment to execute coroutine and launch is a coroutine builder that spawns new coroutine, schedules it for execution in the environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;100_000 threads:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/L6R0sT68kK?from=3"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Above application crashes with java.lang.OutOfMemoryError: unable to create new native thread&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Coroutine Scope Builders
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/" rel="noopener noreferrer"&gt;CoroutineScope&lt;/a&gt; is an interface that has a single abstract property called coroutineContext.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;coroutineContext&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;CoroutineScope is nothing but a CoroutineContext, the only difference is in their intended use. Roman Elizarov explains this in detail in following blog post&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A88%3A88%2F1%2ALoU1WYCDpbNqNj2MKssqAA.jpeg" alt="Roman Elizarov"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Coroutine Context and Scope. Kotlin Coroutines have a context. There… | by Roman Elizarov | Medium&lt;/h2&gt;
      &lt;h3&gt;Roman Elizarov ・ &lt;time&gt;Mar 9, 2019&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fmedium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;



&lt;p&gt;The important thing you need to know is that whenever a new coroutine scope is created, a new job gets created and associated with it.&lt;/p&gt;

&lt;p&gt;Every coroutine created using this scope becomes the child of this job. This is how a parent-child relationship gets created between coroutines. If any of the coroutines throws an unhandled exception, it’s parent job gets canceled which ultimately cancels all its children. This is called &lt;strong&gt;&lt;em&gt;structured concurrency&lt;/em&gt;&lt;/strong&gt;, I highly recommend &lt;a href="https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/" rel="noopener noreferrer"&gt;this&lt;/a&gt; blog to know more on this topic.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to create CoroutineScope
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html" rel="noopener noreferrer"&gt;&lt;strong&gt;MainScope&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is useful for UI components, it creates &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html" rel="noopener noreferrer"&gt;SupervisorJob&lt;/a&gt; and all the coroutines created with this scope runs on the &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html" rel="noopener noreferrer"&gt;Main&lt;/a&gt; thread. Because it creates SupervisorJob, failure of any coroutine does not trigger the termination of others unlike I have mentioned previously in the context of structured concurrency. Failures of child coroutines can be handled using &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-exception-handler/" rel="noopener noreferrer"&gt;CoroutineExceptionHandler&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;MainScope&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ContextScope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SupervisorJob&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Dispatchers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Main&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: To work with the &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html" rel="noopener noreferrer"&gt;Main&lt;/a&gt; dispatcher, following additional platform specific runtime dependencies required to be added to your project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;kotlinx-coroutines-android — for Android Main thread dispatcher&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;kotlinx-coroutines-javafx — for JavaFx Application thread dispatcher&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;kotlinx-coroutines-swing — for Swing EDT dispatcher&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope.html" rel="noopener noreferrer"&gt;&lt;strong&gt;CoroutineScope(ctx)&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This creates a coroutine scope from provided coroutine context and makes sure that a job is associated with this scope.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="nc"&gt;ContextScope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Job&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt; &lt;span class="p"&gt;+&lt;/span&gt; &lt;span class="nc"&gt;Job&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The following example demonstrates creating a new CorotuineScope without any Job passed externally but internally it creates one. It also shows a glimpse of structured concurrency. Child coroutine (C*hild-A*) throws exceptions which result in the cancellation of another coroutine (&lt;em&gt;Child-B&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/WM_y5uczk?from=7"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html" rel="noopener noreferrer"&gt;&lt;strong&gt;coroutineScope(block)&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a suspending function that creates a coroutine scope, new Job and calls provided suspending block with this scope. This inherits coroutine scope from the outer scope and overrides the context’s Job. Note that, this is a suspending function and will return when given block and all its child coroutines are completed even though you do not &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html" rel="noopener noreferrer"&gt;join&lt;/a&gt;/&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html" rel="noopener noreferrer"&gt;await&lt;/a&gt; on coroutines.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;R&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;coroutineScope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;suspend&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;.()&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;R&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;R&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Let’s say you have some asynchronous suspending tasks and you want to wait for results from all of them and then perform some action. In this scenario, you can use coroutineScope, fire all the tasks parallelly and then wait for their results.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/IYOm47v4o?from=7"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/" rel="noopener noreferrer"&gt;&lt;strong&gt;GlobalScope&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a singleton and not associated with any Job. This launches top-level coroutines and highly discouraged to use because if you launch coroutines in the global scope, you lose all the benefits you get from structured concurrency.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="nc"&gt;GlobalScope&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;coroutineContext&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt; &lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;EmptyCoroutineContext&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Following blog post explains more reasons to why you should avoid using GlobalScope&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A88%3A88%2F1%2ALoU1WYCDpbNqNj2MKssqAA.jpeg" alt="Roman Elizarov"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;The reason to avoid GlobalScope. We do not recommend using GlobalScope… | by Roman Elizarov | Medium&lt;/h2&gt;
      &lt;h3&gt;Roman Elizarov ・ &lt;time&gt;Jan 28, 2019&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fmedium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;



&lt;p&gt;The following example demonstrates that there is no Job associated with GlobalScope and the exception is thrown in one of the coroutines launched using GlobalScope does not affect other coroutines hence we loose structured concurrency.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/4NP6osGdy?from=7"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  CoroutineContext
&lt;/h2&gt;

&lt;p&gt;It is simply a map between &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/-key.html" rel="noopener noreferrer"&gt;Key&lt;/a&gt; and &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/-element/index.html" rel="noopener noreferrer"&gt;Element&lt;/a&gt; (Key -&amp;gt; Element) where&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/-key.html" rel="noopener noreferrer"&gt;Key&lt;/a&gt;: Key for the elements of type CoroutineContext&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/-element/index.html" rel="noopener noreferrer"&gt;Element&lt;/a&gt;: Subtype of CoroutineContext, for example, Job, Deferred, CoroutineDispacher, ActorCoroutine, etc.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Problem Statement
&lt;/h3&gt;

&lt;p&gt;Let’s say we have mutable state accessed from different coroutines concurrently and we want this state to be thread-safe.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;There are multiple ways to achieve this but I am going to show using single-threaded executor service.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the following example, 1000 coroutines are created concurrently and each coroutine increments counter value. In the end, asserting that counters value is 1000 proves that there are no race conditions in the solution. You can try printing thread name in the incrementAsyncfunction and verify that all running on the same thread.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/fDUMxcEET?from=8"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/" rel="noopener noreferrer"&gt;&lt;strong&gt;Job&lt;/strong&gt;&lt;/a&gt; &amp;amp; &lt;a href="https://kotlinlang.org/docs/reference/coroutines/basics.html#structured-concurrency" rel="noopener noreferrer"&gt;&lt;strong&gt;Structured Concurrency&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Background job responsible for solely doing side-effects. Conceptually Job is a cancellable thing with lifecycle associated with it.&lt;/p&gt;

&lt;p&gt;Coroutines implement &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/" rel="noopener noreferrer"&gt;Job&lt;/a&gt; interface which is responsible for maintaining the lifecycle of a coroutine.&lt;/p&gt;

&lt;p&gt;Jobs are designed to have a parent-child relationship and this helps a lot in achieving structured concurrency.&lt;/p&gt;

&lt;p&gt;Let’s say we have three jobs A, B, and C. Job B and C are children of Job A. Now if for example Job C fails with an exception other than CancellationException, parent Job A gets notified and A immediately sends termination to other children in this case to Job B. This way structured concurrency is achieved.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2344%2F1%2A8J9bK47rcjHk2kquWNzb-A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2344%2F1%2A8J9bK47rcjHk2kquWNzb-A.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: If the cause of the cancellation is &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellation-exception/index.html" rel="noopener noreferrer"&gt;CancellationExcpetion&lt;/a&gt; then it is considered to be canceled normally hence such cancellations need not start sending termination signals to other siblings via parent.&lt;/p&gt;

&lt;p&gt;A parent-child relation has the following effect:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Cancellation of a parent with [cancel] or its exceptional completion (failure)immediately cancels all its children.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parent cannot complete until all its children are complete.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parent waits for all its children to complete in &lt;em&gt;completing&lt;/em&gt; or &lt;em&gt;canceling&lt;/em&gt; state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Uncaught exception in a child, by default, cancels parent. In particular, this applies to children created with [launch] [CoroutineScope.launch] coroutine builder.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Note that [async][CoroutineScope.async] and other future-like coroutine builders do not have uncaught exceptions by definition since all their exceptions are caught and are encapsulated in their result.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/" rel="noopener noreferrer"&gt;&lt;strong&gt;Deferred&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From the docs: &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/" rel="noopener noreferrer"&gt;Deferred&lt;/a&gt; value is a non-blocking cancellable future; it is a &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job" rel="noopener noreferrer"&gt;Job&lt;/a&gt; with a result.&lt;/p&gt;

&lt;p&gt;Deferred has few additional methods than Job to get completed results either successful or exceptional.&lt;/p&gt;

&lt;h2&gt;
  
  
  Coroutine Builders
&lt;/h2&gt;

&lt;p&gt;There are multiple possible ways to create coroutines based on different requirements. In this section, let’s take a look at a few of them.&lt;/p&gt;

&lt;p&gt;The two most commonly used coroutine builders are launch and async.&lt;/p&gt;

&lt;p&gt;Note that these are extensions to CoroutineScope which means, without coroutine scope, you can not create new coroutine.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html" rel="noopener noreferrer"&gt;&lt;strong&gt;Launch&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This creates new coroutine and returns a reference to coroutine as &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/" rel="noopener noreferrer"&gt;Job&lt;/a&gt;. Using this handle, you can manually cancel launched coroutine using the cancel method available on Job.&lt;/p&gt;

&lt;p&gt;Launch is used to perform asynchronous fire and forget type of operations where you are not interested in the result of the operation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;launch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;EmptyCoroutineContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineStart&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CoroutineStart&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DEFAULT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;suspend&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;.()&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Unit&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Job&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html" rel="noopener noreferrer"&gt;&lt;strong&gt;Async&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This creates new coroutine and returns a reference to coroutine as &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/" rel="noopener noreferrer"&gt;Deferred&lt;/a&gt;. Using this handle, you can manually cancel launched coroutine using the cancel method available on Deferred.&lt;/p&gt;

&lt;p&gt;Async is used to perform asynchronous computation where you expect a result of the computation in the future. Once the result is available, you want to perform other operations using this result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;EmptyCoroutineContext&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineStart&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CoroutineStart&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DEFAULT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;suspend&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;.()&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Deferred&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is very important to note that, when you lunch a coroutine with these constructs, the new job gets created. It inherits the coroutine context and corresponding parent job from where this was launched. The newly created job gets attached to the parent as a child node.&lt;/p&gt;

&lt;p&gt;What is the default behavior of launch and async?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The execution of coroutine starts immediately&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You can override this behavior by passing the different &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/" rel="noopener noreferrer"&gt;CoroutineStart&lt;/a&gt; argument while launching coroutine, for example, &lt;code&gt;start = CoroutineStart.LAZY&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Exceptions in coroutine cancel the parent job in the context which in turn cancels all other coroutines in the same scope&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You can override this behavior by providing explicit &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html" rel="noopener noreferrer"&gt;SupervisorJob&lt;/a&gt; while creating &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html" rel="noopener noreferrer"&gt;CoroutineScope&lt;/a&gt; but this is out of scope for this write-up&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Coroutines get executed on &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html" rel="noopener noreferrer"&gt;Default&lt;/a&gt; &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/index.html" rel="noopener noreferrer"&gt;CoroutineDispatcher&lt;/a&gt;. This is backed by a shared pool of threads and the maximum number of threads is equal to the number of CPU cores (at least two). For example, if you want to perform some IO operation then you can override this behavior by passing custom &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/index.html" rel="noopener noreferrer"&gt;CoroutineContext&lt;/a&gt; like &lt;code&gt;context = Dispatchers.IO&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html" rel="noopener noreferrer"&gt;&lt;strong&gt;withContext&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We often come across a scenario where we want to perform both CPU and IO-bound operations. And it is very important to perform IO-bound operations on a different thread pool (possibly unbounded) than the CPU bound (threads = number of CPU cores). You can find more details on why should we have such segregation in &lt;a href="https://gist.github.com/djspiewak/46b543800958cf61af6efa8e072bfd5c" rel="noopener noreferrer"&gt;this&lt;/a&gt; article&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html" rel="noopener noreferrer"&gt;withContext&lt;/a&gt; construct is exactly designed for this purpose. Following example demonstrate the usage of this:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/4O3yql7oF?from=5"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Above example, &lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html" rel="noopener noreferrer"&gt;withContext&lt;/a&gt; uses dispatcher from the new context, shifting execution of the block into the different thread if a new dispatcher is specified, and back to the original dispatcher when it completes.&lt;/p&gt;

&lt;p&gt;But if you look at the first two lines of output, both got executed on the same thread but the third line got executed on a different thread. This is because IO dispatcher shares threads with a Default dispatcher, so using withContext(Dispatchers.IO) does not lead to an actual switching to another thread &amp;amp; typically execution continues in the same thread. This avoids thread switching costs. But that thread gets marked as IO thread and gets removed from a thread pool. Hence you see line three got executed on a different thread.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="p"&gt;=========&lt;/span&gt; &lt;span class="nc"&gt;Output&lt;/span&gt; &lt;span class="p"&gt;=======&lt;/span&gt;
    &lt;span class="nc"&gt;DefaultDispatcher-worker-1&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="err"&gt;@&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;doing&lt;/span&gt; &lt;span class="nc"&gt;CPU&lt;/span&gt; &lt;span class="n"&gt;work&lt;/span&gt;&lt;span class="err"&gt;…&lt;/span&gt;
    &lt;span class="nc"&gt;DefaultDispatcher-worker-1&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="err"&gt;@&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;doing&lt;/span&gt; &lt;span class="nc"&gt;IO&lt;/span&gt; &lt;span class="n"&gt;work&lt;/span&gt;&lt;span class="err"&gt;…&lt;/span&gt;
    &lt;span class="nc"&gt;DefaultDispatcher-worker-2&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="err"&gt;@&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;back&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="n"&gt;doing&lt;/span&gt; &lt;span class="nc"&gt;CPU&lt;/span&gt; &lt;span class="n"&gt;work&lt;/span&gt;&lt;span class="err"&gt;…&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html" rel="noopener noreferrer"&gt;&lt;strong&gt;runBlocking&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html" rel="noopener noreferrer"&gt;runBlocking&lt;/a&gt; has very limited use cases and highly discouraged. Avoid using this unless it is the last solution to your problem and you know what you are doing.&lt;/p&gt;

&lt;p&gt;runBlocking starts a new coroutine and blocks the current thread until it’s completion. It is designed to bridge regular blocking code and libraries that are written in suspending/non-blocking style. It has very limited use cases, for example,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;you can use runBlocking to block main application so that it will not terminate until all the coroutines launched within the application are completed either successfully or exceptionally&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;runBlocking is very useful in &lt;strong&gt;&lt;em&gt;tests&lt;/em&gt;&lt;/strong&gt;, you can wrap your tests in runBlocking. This will make sure your test code execute sequentially on the same thread and will not terminate until all coroutines are completed. You do not need to explicitly join or await them. Your tests look similar to the tests for synchronous code. In the following example, we want to test the &lt;code&gt;increment&lt;/code&gt; function which increments a counter by &lt;code&gt;1&lt;/code&gt; in async and non-blocking style. Test-should able to increment a counter, calls &lt;code&gt;increment&lt;/code&gt; function &lt;code&gt;50&lt;/code&gt; times and asserts that &lt;code&gt;counter == 50&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;iframe src="https://pl.kotl.in/oO8MCjWEg?from=7"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Find more details on this &lt;a href="https://stackoverflow.com/questions/52331373/kotlin-coroutines-runblocking" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Suspend
&lt;/h2&gt;

&lt;p&gt;We have already come across suspend keyword many times in this post. Let’s go deep into what suspending functions are!&lt;/p&gt;

&lt;p&gt;suspend is a keyword in kotlin which indicates function can be paused and resumed later point in time. You can use suspending functions to call long-running computations without blocking the main thread.&lt;/p&gt;

&lt;p&gt;Rules for calling suspending functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;from other suspending functions&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;from coroutine (suspending functions inherits coroutine context from coroutine from where it is invoked)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Eventually, Kotlin code gets converted to JVM bytecode and there is no notion of suspend keyword on JVM. Under the hood, the kotlin compiler converts suspend functions to another function without the suspend keyword, which takes an additional parameter of type &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-continuation/index.html" rel="noopener noreferrer"&gt;&lt;strong&gt;Continuation&lt;/strong&gt;&lt;/a&gt; which is nothing but a callback.&lt;/p&gt;

&lt;p&gt;Following example shows kotlin suspending function and its compiled version in JVM&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="c1"&gt;// kotlin&lt;/span&gt;
    &lt;span class="k"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;updateUserInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;

    &lt;span class="c1"&gt;// JVM&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="nf"&gt;updateUserInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Continuation&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="n"&gt;completion&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Continuation
&lt;/h2&gt;

&lt;p&gt;Continuation is a simple interface defined in kotlin standard library which has only one method &lt;code&gt;resumeWith(result)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;Continuation&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineContext&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;resumeWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Result&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Since v1.3, Continuation has only one method resumeWith(result: Result) , earlier it used to have two methods resume(value: T) &amp;amp; resumeWithException(exception: Throwable)&lt;br&gt;
&lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html" rel="noopener noreferrer"&gt;Result&lt;/a&gt; models eithersuccess with value of typeT or failure with the exception of type Throwable&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can very well relate this with callback style programming where you have methods like onSuccess and onFailure&lt;/p&gt;

&lt;p&gt;If you are really interested to know how all these things work behind the scenes, I highly recommend you to watch Roman Elizarov talk — Deep Dive into Coroutines.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/YrrUCSi72E8"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;In this talk, Roman Elizarov mentions:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Continuation is a generic callback interface.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;Whenever you invoke suspending function, you actually invoke callback, its just callback is implicit and you don't see it in code. You just code it in nice direct style with callback behind the scenes.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;All the examples used in this article are available &lt;a href="https://github.com/kpritam/kotlin-coroutines/tree/master/blog/src/main/kotlin/blog/scopes" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html" rel="noopener noreferrer"&gt;Coroutines official guide&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://kotlin.github.io/kotlinx.coroutines/" rel="noopener noreferrer"&gt;Coroutines API docs&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.youtube.com/watch?v=_hfBv0a09Jc&amp;amp;list=PLwDsAAKWJGqcuj3CD8gBEabOituAAYrp3" rel="noopener noreferrer"&gt;Coroutines youtube playlist&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/" rel="noopener noreferrer"&gt;Structured concurrency&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055" rel="noopener noreferrer"&gt;Coroutine context and scope&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc" rel="noopener noreferrer"&gt;Reason to avoid Global Scope&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>kotlin</category>
      <category>coroutines</category>
      <category>concurrency</category>
      <category>java</category>
    </item>
  </channel>
</rss>
