⚡ Kotlin Fundamentals
Coroutines & Async Programming
suspend functions, Dispatchers, async/await, structured concurrency.

The Problem: Blocking the UI Thread

Android runs all UI on the main thread. Any blocking call — network request, database query, file read — freezes the UI. If blocked for more than 5 seconds, Android shows an ANR (Application Not Responding) dialog.

⚠️
Never use Thread.sleep() or blocking I/O on the main thread. ANR is the leading cause of one-star app reviews.

Coroutines Basics

kotlin
// Launch a coroutine in ViewModel scope
viewModelScope.launch {
    // Switch to IO thread for network/DB work
    val users = withContext(Dispatchers.IO) {
        api.fetchUsers()
    }
    // Automatically back on Main thread — update UI
    _users.value = users
}

Suspend Functions

kotlin
suspend fun loadProfile(id: String): Profile {
    val user  = withContext(Dispatchers.IO) { db.getUser(id) }
    val posts = withContext(Dispatchers.IO) { api.getPosts(id) }
    return Profile(user, posts)
}

// Parallel execution — both requests run concurrently
suspend fun loadDashboard() = coroutineScope {
    val news    = async { api.getNews() }
    val weather = async { api.getWeather() }
    Dashboard(news.await(), weather.await())
}

C# Equivalent in MAUI

csharp
private async void LoadDataAsync()
{
    IsBusy = true;
    var users = await Task.Run(() => _db.GetAllUsers());
    Users = new ObservableCollection<User>(users);
    IsBusy = false;
}

Key Takeaways

Never block the main thread — use coroutines or C# async/await
Dispatchers.IO runs code on a background thread pool
suspend functions can pause without blocking the thread
async { } + await() runs multiple coroutines concurrently
Lesson 10 of 30Kotlin Fundamentals
← Previous Next Lesson →