title: Kotlin: How to perform an async function and wait for it to finish?
body: <p>I'm writting my first app in Kotlin, so I'm pretty new to this. One of the functions it performs is to read something from an API, and then update the screen based on the result.</p>
  
  <p>I have tried lots of things with the coroutines, but nothing seems to work.</p>
  
  <p>For example, I have something like this:</p>
  
  <pre><code>private fun readAPI() {
      runBlocking {
          fun rAPI() = async {
              val api = "..."
              result = URL(api).readText()
          }
          println(tag, "Result: " + rAPI().await())
      }
  }
  </code></pre>
  
  <p>And lots of different approaches. Nothing seems to work. In the above case I'm getting an exception "android.os.NetworkOnMainThreadException".</p>
  
  <p>The only thig that has worked so far, is something using OkHttp3 as described here: <a href="https://rstopup.com/como-hacer-una-solicitud-a-la-api-de-kotlin.html" rel="noreferrer">https://rstopup.com/como-hacer-una-solicitud-a-la-api-de-kotlin.html</a> (it's in Spanish, but you'll get the idea), and this works, it brings the API response, I parse it, fill in my sqlite3 database and so on. But, since I don't know when the API ends, I can't update the screen controls. And if I try to do it serially, I get an exception that only the thread which started the activity is the one that can update the activity or something like that.</p>
  
  <p>I've seen, and follow LOTS of tutorials that talks about suspend functions, launch, etc., and they try to mimick an API call with <code>delay()</code>, those tutorials work perfectly, until I try to do a real API call.</p>
  
  <p>So, can you point me to a full example on how to call an API with Kotlin, and then update some screen elements?</p>
  
  <p>EDIT
  I'm editing changing the fun by val:</p>
  
  <pre><code>runBlocking {
    val rAPI = async {
      val api = "..."
      URL(api).readText()
    }
    Log.w(tag, rAPI.await())
  }
  </code></pre>
  
  <p>I got the "android.os.NetworkOnMainThreadException" exception.</p>