We use CoroutineScope and dispatchers to run tasks in the background without freezing the app. This helps keep the app smooth and responsive.
0
0
CoroutineScope and dispatchers in Android Kotlin
Introduction
When you want to load data from the internet without stopping the app.
When you need to save information to a database without delay.
When you want to do heavy calculations without freezing the screen.
When you want to update the UI after a background task finishes.
Syntax
Android Kotlin
CoroutineScope(Dispatchers.IO).launch {
// your code here
}CoroutineScope defines where and how coroutines run.
Dispatcher tells the coroutine which thread to use.
Examples
Runs coroutine on the main thread to update UI safely.
Android Kotlin
CoroutineScope(Dispatchers.Main).launch {
// Update UI here
}Runs coroutine on a background thread for input/output tasks.
Android Kotlin
CoroutineScope(Dispatchers.IO).launch {
// Do file or network operations
}Runs coroutine on a background thread optimized for CPU work.
Android Kotlin
CoroutineScope(Dispatchers.Default).launch {
// Perform CPU intensive work
}Sample App
This program creates a coroutine scope with the Default dispatcher. It launches a coroutine that prints the thread name, waits half a second, then prints "Work done". Meanwhile, the main thread prints its name and waits to keep the program alive.
Android Kotlin
import kotlinx.coroutines.* fun main() = runBlocking { val scope = CoroutineScope(Dispatchers.Default) scope.launch { println("Working in background thread: ${Thread.currentThread().name}") delay(500) println("Work done") } println("Main thread: ${Thread.currentThread().name}") delay(1000) // Wait for coroutine to finish }
OutputSuccess
Important Notes
Always choose the right dispatcher to avoid freezing the app.
Use Dispatchers.Main only for UI updates.
Use Dispatchers.IO for network or disk operations.
Summary
CoroutineScope controls where coroutines run.
Dispatchers decide which thread runs the coroutine.
Use dispatchers to keep your app smooth and responsive.