title: How to save data from a Kotlin asynchronous closure?
body: <p>I am calling an API in an asynchronous function, and would like to store the response from the callback.</p>
  
  <p>Specifically, I am using the API category of AWS Amplify in an Android app, and would like to assign the return value to a LiveData variable in a <code>ViewModel</code>.</p>
  
  <pre class="lang-kotlin prettyprint-override"><code>fun getMuscleGroup(id: String): ExampleData {
      var exampleData = ExampleData.builder().name("").build()
  
      Amplify.API.query(
          ModelQuery.get(ExampleData::class.java, id),
          { response -&gt;
              Log.d("AmplifyApi", response.data.name)
              exampleData = response.data
          },
          { error -&gt; Log.e("AmplifyApi", "Query failure", error) }
      )
  
      return exampleData
  }
  </code></pre>
  
  <p>I can receive the response and it gets logged correctly, but the response is not assigned to the <code>exampleData</code> variable, since the function returns early.</p>
  
  <p>In Android Studio, the variable <code>exampleData</code> is highlighted with the text:</p>
  
  <blockquote>
    <p>Wrapped into a reference object to be modified when captured in a closure</p>
  </blockquote>
  
  <p>As I am not that familiar with the multithreading APIs in kotlin, I am not sure, how to block the function until the remote API returns its asynchronous response.</p>