0Pricing
Jetpack Compose Academy · Lesson

suspend Calls in the ViewModel

Fetch data off the main thread.

suspend Calls in the ViewModel is a free Jetpack Compose Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Jetpack Compose Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “suspend Calls in the ViewModel” lesson free?

Yes — the full text of “suspend Calls in the ViewModel” is free to read here on the web, and the Jetpack Compose Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Jetpack Compose Academy course, upgrade to CoddyKit PRO.

What will I learn in “suspend Calls in the ViewModel”?

Fetch data off the main thread. You practise Jetpack Compose Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Jetpack Compose Academy?

No prior experience is required. Jetpack Compose Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “suspend Calls in the ViewModel” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Jetpack Compose Academy lesson?

Yes. Every Jetpack Compose Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Define a Retrofit API Interface
  2. Parsing JSON with Moshi
  3. suspend Calls in the ViewModel
  4. Loading, Success & Error UI
← Back to Jetpack Compose Academy