Junior — Middle
Kuidas erinevad Main dispatcher ja Default dispatcher Kotlinis korutinate kasutamisel?
sobes.tech AI
Vastus AI-lt
In Kotlin, dispatchers determine on which thread or thread pool the coroutine will run.
-
Main dispatcher — is a dispatcher that launches coroutines on the main (UI) thread. Used for updating the interface and interacting with UI elements, where execution on 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 — for the UI thread, Default — for background CPU tasks.