title: How to use a Kotlin coroutine to call a blocking function?
body: <p>I would like to use Kotlin coroutines to call blocking functions.</p>
  <p>For example, I would like to have a suspend function that would &quot;block&quot; until the user responds to a modal dialog, or until a network call returns, when the dialog and network libraries don't provide <code>suspend</code> functions.</p>
  <p>I implemented it using a <code>Mutex</code>.</p>
  <p>For example, for the blocking network call scenario, I did something like this:</p>
  <pre><code>class Connection {
      private val mutex = Mutex()
      
      public suspend fun receive(): ByteArray {
          mutex.lock()
  
          val buf = ByteArray(42)
          
          thread {
              sock.getInputStream().read(buf, 0, 42) // blocking
              mutex.unlock()
          }
  
          mutex.lock()
  
          return buf
      }
  }
  </code></pre>
  <p>It works.</p>
  <p>Please ignore networking-related issues in the above code (like error handling, checking the number of bytes actually read, etc.).</p>
  <p>Please also ignore performance aspects of using a thread (the dedicated thread above is just for the sake of example).</p>
  <p>From the perspective of using a <code>Mutex</code> to &quot;convert&quot; a blocking flow to a coroutines flow:</p>
  <ol>
  <li>Is there a standard or a better way to do this?</li>
  <li>Aside for networking or performance - do you see any downsides to my approach?</li>
  </ol>