Question #374MediumNative Android

What are Kotlin coroutines and how do they differ from threads?

#kotlin#coroutines#concurrency

Answer

Overview

Coroutines are lightweight concurrency primitives that suspend execution instead of blocking threads.


Coroutines vs Threads

FeatureThreadsCoroutines
WeightHeavy (1MB each)Lightweight (~KB)
CostExpensiveCheap
BlockingBlocks threadSuspends (non-blocking)
NumberLimited (~1000s)Unlimited (millions)
CancellationManualBuilt-in

Basic Usage

Threads

kotlin
Thread {
    val data = fetchData()
    runOnUiThread {
        updateUI(data)
    }
}.start()

Coroutines

kotlin
viewModelScope.launch {
    val data = withContext(Dispatchers.IO) {
        fetchData()
    }
    updateUI(data) // Auto on main thread
}

Dispatchers

kotlin
// Main thread (UI updates)
Dispatchers.Main

// Background (network, DB)
Dispatchers.IO

// CPU-intensive work
Dispatchers.Default

async/await

kotlin
viewModelScope.launch {
    val user = async { fetchUser() }
    val posts = async { fetchPosts() }
    
    val userData = user.await()
    val postsData = posts.await()
}

Cancellation

kotlin
val job = viewModelScope.launch {
    repeat(1000) {
        delay(100)
        // Work
    }
}

job.cancel() // ✅ Clean cancellation

Structured Concurrency

kotlin
viewModelScope.launch {
    val job1 = launch { task1() }
    val job2 = launch { task2() }
    // Both cancelled when viewModelScope is cleared
}

Key Advantage: 10,000 coroutines use same memory as 10 threads.