Coroutine dispatcher confined to a single thread

You must never use runBlocking inside the coroutine. Especially inside default dispatcher because it will eventually block the whole pool. The feature you are searching for is called context switch and achieved by withContext function or additional CoroutineContext launch argument. Like this:

val singleDispatcher = Executors.newSigleThreadExecutor().asCoroutineDispatcher()
// ...
launch(Dispatchers.Default){
  // do something multithreaded...
  val res = withContext(singleDispatcher){
    // do somthething on a single thread...
  }//return to Default
}
1 Like