title: How to call asynchronous request synchronously with a timeout value?
body: <p>I have to synchronously call an asynchronous api request. Since this api request takes long time to answer, I also want to set a timeout to fail the api-request and continue with null. Here's my code to call this api:</p>
  <pre><code>private suspend fun call(
      accessStage: AccessStage,
  ): Response? = withContext&lt;Response?&gt;(Dispatchers.IO) {
  
      return@withContext withTimeoutOrNull(1000) {
  
          suspendCoroutine&lt;Response?&gt; { continuation -&gt;
  
              val request = External3rdPartyApi.newRequest(
                  accessStage
              ) { response, throwable -&gt;
  
                  continuation.resume(response)
              }
  
              request.parameters = hashMapOf&lt;String, String&gt;().apply {
                  put[&quot;token&quot;] = External3rdPartyApi.TOKEN
                  put[&quot;salt&quot;] = External3rdPartyApi.calculateSalt(accessStage)
              }
              request.executeAsync()
          }
      }
  }
  </code></pre>
  <p>I can't change how <code>External3rdPartyApi</code> works.</p>
  <p>I think above code looks evil. Also, I read in <a href="https://stackoverflow.com/a/47641886/3682535">another answer</a>:</p>
  <blockquote>
  <p><code>withTimeout { ... }</code> is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is <em>cancellable</em>.</p>
  </blockquote>
  <p>So, should I use <code>suspendCancellableCoroutine</code> instead of <code>suspendCoroutine</code>?</p>
  <p>How can I write it in a better way?</p>