Kotlin & Coroutines (50 Qs)•Part 1: Core Language, Type System & Syntax (1 - 10)
How does Kotlin Coroutines integrate with Android Lifecycles (Dispatchers & Scopes)?
junior LevelCode ExampleLifecycle
In Simple Words: Coroutines provide lightweight, non-blocking asynchronous programming on Android:
- Dispatchers:
Dispatchers.Main: Executes on the Android UI thread. For UI updates and small operations.Dispatchers.IO: Optimized for disk and network I/O operations (Room queries, Retrofit HTTP calls).Dispatchers.Default: Optimized for CPU-intensive background computation (parsing large JSON arrays, image filtering).
- Lifecycle Scopes:
viewModelScope: Tied to the ViewModel lifecycle; automatically cancels all running coroutines when the ViewModel is cleared, preventing memory leaks!lifecycleScope: Tied to an Activity or Fragment lifecycle.
kotlin
class UserViewModel(private val repository: UserRepository) : ViewModel() {
fun fetchUserProfile(userId: String) {
viewModelScope.launch {
// Automatically switches to Dispatchers.IO under the hood:
val user = repository.getUser(userId)
// Resumes on Dispatchers.Main to update UI state:
_uiState.value = UserUiState.Success(user)
}
}
}