Sobes.tech
Junior — Middle

What methods can be used to change the coroutine dispatcher in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, there are several ways to change the coroutine dispatcher:

  1. Passing the dispatcher when launching a coroutine
import kotlinx.coroutines.*

GlobalScope.launch(Dispatchers.IO) {
    // Code runs in IO dispatcher
}
  1. Using the withContext function to switch dispatchers inside a coroutine
suspend fun loadData() {
    withContext(Dispatchers.Default) {
        // Executes on another dispatcher
    }
}
  1. Creating a custom dispatcher using newSingleThreadContext or newFixedThreadPoolContext
val myDispatcher = newSingleThreadContext("MyThread")

GlobalScope.launch(myDispatcher) {
    // Executes in its own thread
}

Thus, the dispatcher can be changed when launching a coroutine or inside it using withContext.