Data & Networking · 8 min read · Intermediate
Kotlin Coroutines & Structured Concurrency
Run network and disk work off the Main thread with `suspend` functions, `Dispatchers.IO`, and `viewModelScope`.
What you'll learn
- Mark async functions with `suspend`
- Switch threads cleanly with `withContext(Dispatchers.IO)`
- Handle errors explicitly with `runCatching` or `try/catch`
Overview
Run network and disk work off the Main thread with suspend functions, Dispatchers.IO, and viewModelScope.
Code Example
fun loadCourses() {
viewModelScope.launch {
_uiState.value = UiState.Loading
val result = runCatching {
withContext(Dispatchers.IO) { repository.fetchCourses() }
}
_uiState.value = result.fold(
onSuccess = { UiState.Success(it) },
onFailure = { UiState.Error(it.message ?: "Network error") },
)
}
}
Key Takeaways
- Mark async functions with
suspend - Switch threads cleanly with
withContext(Dispatchers.IO) - Handle errors explicitly with
runCatchingortry/catch
Quick Check
Check Your Understanding
Score: 0 / 1
1. What happens if an Android app runs a 6-second blocking network call directly on the Main thread?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.