Work.kt
  1. 1suspend fun loadLesson(id: String): Lesson =
  2. 2 withContext(Dispatchers.IO) {
  3. 3 source.read(id)
  4. 4 }

Work.kt

Coroutines stay off the main thread

A coroutine is not a thread you name by hand. It is a unit of work that can pause without blocking the thread it was using. suspend tells the caller that the function may wait.

Dispatchers.Main is where Compose and views touch the UI. Dispatchers.IO is where a disk or network read belongs. withContext moves the work and brings the result back.

viewModelScope cancels the work when the screen owner is cleared. A lesson that launches in GlobalScope keeps running after the reader has left. This desk does not teach that habit.

Danville · educational · 2018AboutDeskFAQOffice