🤖
Droidly
Coroutines
30-second explainer
Coroutine
Lifecycle
How launch, suspend & cancel really work
▶ Auto-playing
MyViewModel.kt
class
MyViewModel
:
ViewModel
() {
init
{
viewModelScope.
launch
{
// 🚀 coroutine body
loadDashboard
()
}
}
}
viewModelScope
Tied to ViewModel lifecycle — auto-cancelled when ViewModel is cleared
.launch { }
Starts a new coroutine on Main dispatcher. Non-blocking & structured
MyViewModel.kt
viewModelScope.
launch
{
// Main thread ↓
val
data =
withContext
(
Dispatchers
.IO) {
repository.
fetchData
()
// IO thread — suspend
}
// resumes on Main ↑
_state.value = data
}
Main
──suspends──▶
Dispatchers.IO
──resumes──▶
Main
Never blocks UI 🎯
What happens when you leave the screen?
🚪
ViewModel
.
onCleared
()
User navigates away
↓
⚡
viewModelScope
.
cancel
()
Scope is cancelled
↓
✅
CancellationException
thrown
Coroutine exits safely
Key Takeaways 🎓
🔗
viewModelScope
auto-cancels — zero manual cleanup needed
⏸️
suspend
pauses the coroutine, not the thread — UI stays smooth
🧵
Use
Dispatchers.IO
for network/disk,
Default
for CPU-heavy work
0:00
↺ Replay