Junior — Middle
Can you explain what CoroutineDispatcher is and how it is used in coroutine programming?
sobes.tech AI
Answer from AI
CoroutineDispatcher in Kotlin is an abstraction that determines which thread or thread pool will execute the coroutine. It is responsible for scheduling and distributing coroutine tasks.
Main points:
Dispatchers.Main— for execution on the main (UI) thread.Dispatchers.IO— optimized for input/output operations.Dispatchers.Default— for CPU-intensive tasks.
Using CoroutineDispatcher allows controlling exactly where the coroutine code runs, which is important for performance and correctness (for example, UI updates should happen on the main thread).
Example:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch(Dispatchers.IO) {
// Execution in IO thread pool
println("Running on thread: ${Thread.currentThread().name}")
}
}
Thus, CoroutineDispatcher is a tool for managing the execution context of coroutines.