title: Kotlin: withContext() vs Async-await
body: <p>I have been reading <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md" rel="noreferrer">kotlin docs</a>, and if I understood correctly the two Kotlin functions work as follows :</p>
  <ol>
  <li><code>withContext(context)</code>: switches the context of the current coroutine, when the given block executes, the coroutine switches back to previous context.</li>
  <li><code>async(context)</code>: Starts a new coroutine in the given context and if we call <code>.await()</code> on the returned <code>Deferred</code> task, it will suspends the calling coroutine and resume when the block executing inside the spawned coroutine returns.</li>
  </ol>
  <p>Now for the following two versions of <code>code</code> :</p>
  <p><strong>Version1:</strong></p>
  <pre><code>  launch(){
      block1()
      val returned = async(context){
        block2()
      }.await()
      block3()
    }
  </code></pre>
  <p><strong>Version2:</strong></p>
  <pre><code>  launch(){
      block1()
       val returned = withContext(context){
        block2()
      }
      block3()
    }
  </code></pre>
  <ol>
  <li>In both versions block1(), block3() execute in default context(commonpool?) where as block2() executes in the given context.</li>
  <li>The overall execution is synchronous with block1() -&gt; block2() -&gt; block3() order.</li>
  <li>Only difference I see is that version1 creates another coroutine, where as version2 executes only one coroutine while switching context.</li>
  </ol>
  <p>My questions are :</p>
  <ol>
  <li><p>Isn't it always better to use <code>withContext</code> rather than <code>async-await</code> as it is functionally similar, but doesn't create another coroutine. Large numbers of coroutines, although lightweight, could still be a problem in demanding applications.</p>
  </li>
  <li><p>Is there a case <code>async-await</code> is more preferable to <code>withContext</code>?</p>
  </li>
  </ol>
  <p><strong>Update:</strong>
  <a href="https://blog.jetbrains.com/kotlin/2018/06/kotlin-1-2-50-is-out/" rel="noreferrer">Kotlin 1.2.50</a> now has a code inspection where it can convert <code>async(ctx) { }.await() to withContext(ctx) { }</code>.</p>