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
| Feature | Threads | Coroutines |
|---|---|---|
| Weight | Heavy (1MB each) | Lightweight (~KB) |
| Cost | Expensive | Cheap |
| Blocking | Blocks thread | Suspends (non-blocking) |
| Number | Limited (~1000s) | Unlimited (millions) |
| Cancellation | Manual | Built-in |
Basic Usage
Threads
kotlinThread { val data = fetchData() runOnUiThread { updateUI(data) } }.start()
Coroutines
kotlinviewModelScope.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
kotlinviewModelScope.launch { val user = async { fetchUser() } val posts = async { fetchPosts() } val userData = user.await() val postsData = posts.await() }
Cancellation
kotlinval job = viewModelScope.launch { repeat(1000) { delay(100) // Work } } job.cancel() // ✅ Clean cancellation
Structured Concurrency
kotlinviewModelScope.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.