0Pricing
Android Academy · Lesson

viewModelScope and Dispatchers

Run work on the correct thread.

viewModelScope and Dispatchers is a free Android Academy lesson on CoddyKit — lesson 2 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 Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Lifecycle-Aware Scopes

Android gives you built-in scopes that cancel automatically:

  • viewModelScope — cancelled when the ViewModel is cleared.
  • lifecycleScope — tied to an Activity/Fragment lifecycle.

Using viewModelScope

Launch data work in viewModelScope. When the ViewModel is cleared, the coroutine is cancelled for you — no manual cleanup.

class UserViewModel(
    private val repo: UserRepository
) : ViewModel() {
    fun load() {
        viewModelScope.launch {
            val users = repo.getUsers()
            _uiState.value = UiState(users)
        }
    }
}

Why Not GlobalScope

Avoid GlobalScope: its coroutines live for the whole app and are never tied to a lifecycle, causing leaks and work that continues after the screen is gone.

What Are Dispatchers?

A Dispatcher decides which thread (or pool) a coroutine runs on. Choosing the right one keeps the main thread free.

The Standard Dispatchers

  • Dispatchers.Main — the UI thread.
  • Dispatchers.IO — for network and disk I/O.
  • Dispatchers.Default — for CPU-intensive work.

viewModelScope Defaults to Main

viewModelScope launches on Dispatchers.Main. That is fine for updating state, but you should move heavy work off it.

Switching with withContext

Use withContext to run a block on a different dispatcher, then return to the caller.

suspend fun loadFile(): String =
    withContext(Dispatchers.IO) {
        File("data.txt").readText()
    }

Main-Safe Functions

A function is main-safe if it is safe to call from the main thread because it switches internally. Repositories should be main-safe so callers never worry about threads.

class Repo {
    suspend fun getUsers() =
        withContext(Dispatchers.IO) { dao.getAll() }
}

Room and Retrofit Are Main-Safe

Good news: Room suspend DAO methods and Retrofit suspend calls already run off the main thread. You usually do not need an explicit withContext for them.

CPU Work on Default

For heavy computation like sorting a huge list or parsing, use Dispatchers.Default to avoid janking the UI.

val sorted = withContext(Dispatchers.Default) {
    bigList.sortedBy { it.score }
}

Injecting Dispatchers

For testability, inject dispatchers instead of hardcoding them. This lets tests swap in a test dispatcher.

class Repo(
    private val io: CoroutineDispatcher = Dispatchers.IO
) {
    suspend fun load() = withContext(io) { /* ... */ }
}

Quick Check

Test your understanding of scopes and dispatchers.

Recap

You learned:

  • viewModelScope cancels coroutines when the ViewModel clears.
  • Avoid GlobalScope.
  • Pick dispatchers: Main (UI), IO (network/disk), Default (CPU).
  • withContext switches threads; aim for main-safe functions.

Frequently asked questions

Is the “viewModelScope and Dispatchers” lesson free?

Yes — the full text of “viewModelScope and Dispatchers” is free to read here on the web, and the Android 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 Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “viewModelScope and Dispatchers”?

Run work on the correct thread. You practise Android 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 Android Academy?

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

How long does the “viewModelScope and Dispatchers” 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 Android Academy lesson?

Yes. Every Android 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. Coroutine Basics and Scopes
  2. viewModelScope and Dispatchers
  3. Kotlin Flow Basics
  4. StateFlow and SharedFlow
← Back to Android Academy