0Pricing
Jetpack Compose Academy · Lektion

suspend-Aufrufe im ViewModel

Rufen Sie Daten abseits des Hauptthreads ab.

suspend-Aufrufe im ViewModel ist eine kostenlose Jetpack Compose Academy-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Jetpack Compose Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Jetpack Compose Academy-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.users

Cancellation 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.

Häufig gestellte Fragen

Ist die Lektion „suspend-Aufrufe im ViewModel“ kostenlos?

Ja — der vollständige Text von „suspend-Aufrufe im ViewModel“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Jetpack Compose Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Jetpack Compose Academy-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „suspend-Aufrufe im ViewModel“?

Rufen Sie Daten abseits des Hauptthreads ab. Du übst Jetpack Compose Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Jetpack Compose Academy zu starten?

Keine Vorkenntnisse erforderlich. Jetpack Compose Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.

Wie lange dauert die Lektion „suspend-Aufrufe im ViewModel“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Jetpack Compose Academy-Lektion Code schreiben und ausführen?

Ja. Jede Jetpack Compose Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Ein Retrofit-API-Interface definieren
  2. JSON mit Moshi parsen
  3. suspend-Aufrufe im ViewModel
  4. UI für Laden, Erfolg und Fehler
← Zurück zu Jetpack Compose Academy