stefano
stefano

Reputation: 73

Transfer Coroutine Dispatcher's Tasks to another Dispatcher

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

Upvotes: 0

Views: 167

Answers (1)

Xid
Xid

Reputation: 4951

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
}

Upvotes: 1

Related Questions