Coroutines 是 Kotlin 的异步编程解决方案——编写异步代码(网络调用、数据库操作)以顺序的方式读取而不阻塞主线程。它们是 Android 中处理异步工作的现代、推荐方式,避免了回调的复杂性。
为什么异步在 Android 中很重要
The MAIN (UI) thread must stay responsive — blocking it (with network/DB work) freezes
the UI (ANR "Application Not Responding" errors):
→ long operations MUST run off the main thread (asynchronously)
→ old approaches: callbacks (nested, complex), threads/AsyncTask (verbose, error-prone)
→ COROUTINES make async code clean and sequential.
Coroutines:看起来顺序的异步代码
: User {
user = api.getUser()
posts = api.getPosts(user)
user
}
viewModelScope.launch {
user = loadUser()
updateUi(user)
}
