0Pricing
Jetpack Compose Academy · Lezione

Chiamate suspend nel ViewModel

Recuperi i dati al di fuori del thread principale.

Chiamate suspend nel ViewModel è una lezione Jetpack Compose Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Jetpack Compose Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Chiamate suspend nel ViewModel» è gratuita?

Sì — il testo completo di «Chiamate suspend nel ViewModel» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Jetpack Compose Academy, passa a CoddyKit PRO. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Cosa imparerò in «Chiamate suspend nel ViewModel»?

Recuperi i dati al di fuori del thread principale. Eserciti Jetpack Compose Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Jetpack Compose Academy?

Non è richiesta alcuna esperienza precedente. Jetpack Compose Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Chiamate suspend nel ViewModel»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Jetpack Compose Academy?

Sì. Ogni lezione Jetpack Compose Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire un'interfaccia API Retrofit
  2. Analizzare JSON con Moshi
  3. Chiamate suspend nel ViewModel
  4. UI di caricamento, successo ed errore
← Torna a Jetpack Compose Academy