ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Kotlin Tutorial• 8 min read

Kotlin Coroutines & Lightweight Threads

suspend functions, Dispatchers.IO, Dispatchers.Main, and launch/async

Coroutines are lightweight threads that can be suspended without blocking the underlying OS thread, enabling high-performance non-blocking asynchronous programming.

Suspending Functions vs Blocking Threads

A traditional OS thread consumes ~1MB of memory. You can easily spawn 100,000 coroutines on a single machine without crashing!

suspend: Marks a function that can pause execution without blocking the calling thread.

Dispatchers.Main: Runs on the Android UI thread for updating views.

Dispatchers.IO: Optimized for disk I/O and network operations.

withContext(Dispatchers.IO): Safely switches execution to background thread pools.

Fetching Network Data with Coroutines
import kotlinx.coroutines.*

suspend fun fetchUserProfile(userId: String): String {
    // Switch to IO thread for network latency
    return withContext(Dispatchers.IO) {
        delay(1000) // Non-blocking coroutine suspension
        "UserData for ID: $userId"
    }
}

fun main() = runBlocking {
    println("Fetching user profile...")
    val profile = fetchUserProfile("usr_981")
    println("Received: $profile")
}
delay() pauses without blocking OS worker threads.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which keyword marks a Kotlin function that can pause its execution without blocking the underlying OS thread?