Home > database >  Transfer Coroutine Dispatcher's Tasks to another Dispatcher
Transfer Coroutine Dispatcher's Tasks to another Dispatcher

Time:06-20

My question is simple, given Dispatcher 1, how would you transfer Dispatcher 1's tasks to another Dispatcher named Dispatcher 2?

CodePudding user response:

Not sure what transfer would mean but yes you can jump between threads. You can use withContext within a coroutine to switch between threads. Like so:

val customContext = newSingleThreadContext("CustomContext")

runBlocking(Dispatchers.Default) {
    // Started in DefaultDispatcher
    withContext(customContext) {
        // Working in CustomContext
    }
    // Back to DefaultDispatcher
}
runBlocking(Dispatchers.Unconfined) {
    // Started in main thread
    withContext(Dispatchers.Default) {
        // Working in DefaultDispatcher
    }
    // Back to main thread
}
  • Related