Junior — Middle
Can you explain what is meant by the term 'Dispatchers' and how they are used?
sobes.tech AI
Answer from AI
In Kotlin Coroutines, Dispatchers are objects that determine on which thread or thread pool a coroutine will be executed.
Main types of dispatchers:
Dispatchers.Main— for working with the UI thread (e.g., in Android).Dispatchers.IO— for input/output operations, such as reading files or network requests.Dispatchers.Default— for CPU-intensive tasks.Dispatchers.Unconfined— starts the coroutine in the current thread but can switch.
Usage:
GlobalScope.launch(Dispatchers.IO) {
// runs in an IO thread pool
val data = fetchData()
withContext(Dispatchers.Main) {
// update UI
updateUI(data)
}
}
Thus, Dispatchers help efficiently manage threads and avoid blocking the UI.