コルーチンはKotlinの非同期プログラミング向けソリューション — ネットワーク呼び出しやデータベース操作などの非同期コード(async code)をメインスレッドをブロックせずに順序立てて読むことができます。これは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.
コルーチン:順序立てて見える非同期コード
: User {
user = api.getUser()
posts = api.getPosts(user)
user
}
viewModelScope.launch {
user = loadUser()
updateUi(user)
}
