Junior — Middle
What types of CoroutineDispatcher are you familiar with and in what cases have you used them?
sobes.tech AI
Answer from AI
In Kotlin Coroutines, there are several main types of CoroutineDispatcher that determine in which thread or thread pool the coroutine will be executed:
- Dispatchers.Main — used for working with the UI thread, for example, in Android to update the interface.
- Dispatchers.IO — optimized for input/output operations, such as working with files, network, or databases. Uses a thread pool that can expand.
- Dispatchers.Default — used for CPU-intensive tasks, such as calculations and data processing.
- Dispatchers.Unconfined — starts the coroutine in the current thread until the first suspension, then continues in the thread where it was resumed.
Example of usage:
launch(Dispatchers.IO) {
val data = fetchDataFromNetwork()
withContext(Dispatchers.Main) {
updateUI(data)
}
}
Here, the network request is performed in the IO dispatcher, and the UI update is in the main thread.