Sobes.tech
Junior — Middle

Can you list the different types of CoroutineDispatcher used in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, different types of CoroutineDispatcher are used to manage the execution context of coroutines. The main ones are:

  • Dispatchers.Main — used for executing coroutines on the main (UI) thread, for example, to update the interface.
  • Dispatchers.IO — optimized for input/output operations, such as working with files, network, or database.
  • Dispatchers.Default — intended 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 resumes.

You can also create your own dispatchers based on thread pools using newSingleThreadContext or newFixedThreadPoolContext.

Example usage:

launch(Dispatchers.IO) {
    // Perform network request
}

launch(Dispatchers.Main) {
    // Update UI
}