ViewModel内のsuspend呼び出し
メインスレッド外でデータを取得します。
「ViewModel内のsuspend呼び出し」はCoddyKit上の無料Jetpack Compose Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはJetpack Compose Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Jetpack Compose Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Never Block the Main Thread
Network calls take time, and doing them on the UI thread freezes your app. You move that work off the main thread instead.
Make the Endpoint suspend
Mark your Retrofit function with the suspend keyword. Now it returns the parsed result directly and can pause without blocking. ⏸️
@GET("users")
suspend fun getUsers(): List<User>The ViewModel Owns the Logic
Fetching data belongs in the ViewModel, not the Composable. It survives rotation and keeps your UI code purely about display.
class UserViewModel : ViewModel() {
// network logic lives here
}Launch With viewModelScope
A suspend function needs a coroutine. viewModelScope gives you one that is cancelled automatically when the ViewModel clears.
viewModelScope.launch {
val users = api.getUsers()
}Store the Result in State
Once the call returns, save the data into a state property so Compose can observe it and redraw the screen.
var users by mutableStateOf<List<User>>(emptyList())Wrap It In a try-catch
Networks fail, so guard the call with try-catch. An unhandled exception in a coroutine can crash your whole app.
try {
users = api.getUsers()
} catch (e: Exception) {
// handle failure
}Fetch on Init
Trigger the first load in the ViewModel's init block, so data starts arriving the moment the screen is created.
init {
loadUsers()
}Keep It in a Function
Wrap the fetch in a named function like loadUsers. That makes it easy to call again for retry or pull-to-refresh.
fun loadUsers() = viewModelScope.launch {
users = api.getUsers()
}Dispatchers Handle Threading
Retrofit already runs the request on a background dispatcher, so you usually don't switch threads with Dispatchers.IO yourself.
Collect State in Compose
In your Composable, read the ViewModel's state. Because it's observable, Compose recomposes the instant fresh data lands.
val users = viewModel.usersCancellation Is Automatic
If the user leaves and the ViewModel clears, viewModelScope cancels the in-flight call, so you waste no work on a dead screen.
Quick Check
Which scope cancels its coroutines automatically when the ViewModel is cleared?
Recap: Calling From the ViewModel
You made endpoints suspend, launched them in viewModelScope, stored results in state, and caught errors. Next you'll render loading, success, and error states.
よくある質問
「ViewModel内のsuspend呼び出し」レッスンは無料ですか?
はい。「ViewModel内のsuspend呼び出し」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Jetpack Compose Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Jetpack Compose Academyコースには全4レッスンが含まれています。
「ViewModel内のsuspend呼び出し」で何を学びますか?
メインスレッド外でデータを取得します。 ブラウザで直接実行するハンズオンコードでJetpack Compose Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Jetpack Compose Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのJetpack Compose Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「ViewModel内のsuspend呼び出し」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このJetpack Compose Academyレッスンでコードを書いて実行できますか?
はい。すべてのJetpack Compose Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Retrofit APIインターフェースを定義する
- MoshiでJSONを解析する
- ViewModel内のsuspend呼び出し
- 読み込み、成功、エラーのUI