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:
- Passing the dispatcher when launching a coroutine
import kotlinx.coroutines.*
GlobalScope.launch(Dispatchers.IO) {
// Code runs in IO dispatcher
}
- Using the
withContextfunction to switch dispatchers inside a coroutine
suspend fun loadData() {
withContext(Dispatchers.Default) {
// Executes on another dispatcher
}
}
- Creating a custom dispatcher using
newSingleThreadContextornewFixedThreadPoolContext
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.