title: Kotlin coroutine await on UI thread
body: <p>At the moment in my codebase, using <code>Kotlin</code>, I have an extension function that works in the following manner.</p>
  
  <pre><code>async {
      executeSomeCodeToGetResult()
  }.awaitOnUiThread { result -&gt;
      useResultOnUiThread(result)
  }
  </code></pre>
  
  <p>The <code>async</code> function loads a runnable onto an <code>ExecutorService</code> which returns a <code>Future&lt;T&gt;</code> result. <code>awaitOnUiThread</code> is an extension function on the <code>Future&lt;T&gt;</code> object that sends <code>T</code> as an argument to the input function.</p>
  
  <p>I was wondering if there is a way using <code>Kotlin</code> <code>coroutines</code> to achieve a similar result?</p>
  
  <p>I did implement something like this but I didn't get very good performance results. Maybe I'm doing something wrong running the <code>await()</code> function on the <code>GlobalScope</code>?</p>
  
  <pre><code>private const val threadPoolSize = 4
  
  @ObsoleteCoroutinesApi
  val scope = CoroutineScope(newFixedThreadPoolContext(threadPoolSize, "async-runner"))
  
  @ObsoleteCoroutinesApi
  fun &lt;T&gt; async(function: () -&gt; T): Deferred&lt;T&gt; {
      return scope.async { function() }
  }
  
  fun &lt;T&gt; Deferred&lt;T&gt;.awaitOnUiThread(function: (T) -&gt; Unit) {
      val deferred = this
      GlobalScope.launch {
          val result: T = deferred.await()
          Handler(Looper.getMainLooper()).post {
              function(result)
          }
      }
  }
  </code></pre>