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
- Coroutine Basics and Scopes
- viewModelScope and Dispatchers
- Kotlin Flow Basics
- StateFlow and SharedFlow