0Pricing
Android Academy · Lesson

viewModelScope and Dispatchers

Run work on the correct thread.

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)
        }
    }
}

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