1. Coroutine
A coroutine is the actual background task.
Example:
launch {
api.getProfile()
}
Here, the work is:
api.getProfile()
So coroutine means:
A lightweight task that can run without blocking the main thread.
2. CoroutineScope
A CoroutineScope is like a container/manager for coroutines.
It decides:
Where coroutine runs
How long coroutine lives
When coroutine should be cancelled
Example:
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
// coroutine work
}
Here:
scope = manager
launch block = coroutine
3. viewModelScope
viewModelScope is a special CoroutineScope given by Android to every ViewModel.
Example:
class ProfileViewModel : ViewModel() {
fun loadProfile() {
viewModelScope.launch {
repository.getProfile()
}
}
}
Meaning:
Run this coroutine inside the ViewModel’s scope.
4. Relationship
Very important:
CoroutineScope is the general concept.
viewModelScope is one specific CoroutineScope.
Coroutine is the actual task running inside the scope.
Like this:
ViewModel
owns
viewModelScope
manages
coroutines
Visual:
ProfileViewModel
│
└── viewModelScope
│
├── coroutine 1 → API call
├── coroutine 2 → DB operation
└── coroutine 3 → file operation
5. Why use viewModelScope?
Because it automatically cancels coroutines when ViewModel is cleared.
viewModelScope.launch {
delay(10000)
println("Done")
}
If user leaves the screen before 10 seconds:
Screen closed
↓
ViewModel cleared
↓
viewModelScope cancelled
↓
Coroutine cancelled
So "Done" will not print.
6. Without viewModelScope
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
delay(10000)
println("Done")
}
Here you created the scope manually.
So you must cancel it manually:
scope.cancel()
Otherwise it may continue even after the screen is gone.
7. Final Note
Write this in your notes:
Coroutine = actual background task.
CoroutineScope = manager/container that controls coroutines.
viewModelScope = Android-provided CoroutineScope attached to ViewModel.
When ViewModel is cleared, viewModelScope is automatically cancelled.
So all coroutines launched inside viewModelScope are also cancelled.
Best simple line:
viewModelScope.launch { } means:
Run this coroutine as long as the ViewModel is alive.
Top comments (0)