Sobes.tech
Junior — Middle

How do Main dispatcher and Default dispatcher differ when using coroutines in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin coroutines, dispatchers determine which thread or thread pool will execute the coroutine.

  • Main dispatcher — is the dispatcher that launches coroutines on the main (UI) thread. It is used for updating the interface and interacting with UI elements, where execution in the main thread is required.

  • Default dispatcher — is the default dispatcher that uses a thread pool optimized for CPU-intensive tasks. It does not block the main thread and is suitable for background computations.

Example:

// Launching a coroutine on the main thread
CoroutineScope(Dispatchers.Main).launch {
    // update UI
}

// Launching a coroutine for background work
CoroutineScope(Dispatchers.Default).launch {
    // heavy computations
}

In summary, Main dispatcher is for the UI thread, Default is for background CPU tasks.