title: Kotlin Coroutine launch{} vs launch{ withContext{} }
body: <p>My Android app need to do some file read/write in background (inside a Service), first I use:</p>
  <pre><code>CoroutineScope(Dispatchers.IO).launch {
      val fos = openFileOutput(fileName, MODE_PRIVATE)
      val oos = ObjectOutputStream(fos)
      oos.writeObject(myObj)
      oos.close()
  }
  </code></pre>
  <p>Every single line inside the block has a warning: &quot;Inappropriate blocking method call&quot;</p>
  <p>After search the problem, I think I understand 80% of it. So basically most Coroutine only has 1 thread, if it is blocked, that coroutine will have no thread to do other job. To fix this, we should wrap it inside <code>withContext</code> like this:</p>
  <pre><code>CoroutineScope(Dispatchers.IO).launch {
      withContext(Dispatchers.IO) {
          val fos = openFileOutput(fileName, MODE_PRIVATE)
          val oos = ObjectOutputStream(fos)
          oos.writeObject(myObj)
          oos.close()
      }
  }
  </code></pre>
  <p>Android Studio still shows the warning. <a href="https://stackoverflow.com/questions/58680028/how-to-make-inappropriate-blocking-method-call-appropriate">The post</a> say it is just a bug in Android Studio, and this solution is fine.</p>
  <p>What I don't understand is, <code>withContext</code> is still run on <code>Dispatchers.IO</code>. From the <code>launch</code> block, it may seem like non-blocking, but if <code>Dispatchers.IO</code> only has 1 thread and the <code>withContext</code> block is run on that thread, then that thread is still blocked isn't it?</p>
  <p>I also learned <code>Dispatchers.IO</code> actually has virtually infinite threads, it just create a new one when needed. So the <code>withContext</code> actually is not blocking, but if this is true, why do we need the <code>withContext</code> block? The first code won't have any problem if <code>Dispatchers.IO</code> can create thread when needed thus will never be blocked, right?</p>