Android Academy · Lesson

viewModelScope and Dispatchers

Run work on the correct thread.

Lesson 2 of 413 steps

viewModelScope and Dispatchers is a free Android Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 4 lessons in total.

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.
Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
36
Lessons
152

Frequently Asked Questions

Is the “viewModelScope and Dispatchers” lesson free?

Yes — any 3 lessons of the Android Academy learning path, including “viewModelScope and Dispatchers”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

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