Interview frequency: …
Short answer
Main is for the UI and interaction, IO is for input/output and network operations, Default is for CPU-intensive computation, and Unconfined starts on the current thread without restriction.
Explanation
Dispatchers.Main runs tasks on the UI thread. Dispatchers.IO has a flexible thread pool (up to 64 threads by default) and is designed for long-waiting operations such as reading files, network, and databases. Dispatchers.Default relies on the number of CPU cores and suits image processing, large JSON, and complex algorithms.
Code example
// Use withContext to switch smoothly between threads:
suspend fun loadAndParseData(): Result = withContext(Dispatchers.IO) {
val rawJson = networkClient.download() // IO work
withContext(Dispatchers.Default) {
parseHeavyJson(rawJson) // CPU work
}
}Common mistakes
- Decoding huge images or sorting giant lists on Dispatchers.IO instead of Dispatchers.Default.
- Running database queries or network calls on Dispatchers.Main, causing UI freezes and ANRs.