Junior — Middle
How to initiate the execution of a coroutine within a ViewModel?
sobes.tech AI
Answer from AI
In Android, to launch a coroutine in a ViewModel, viewModelScope is usually used, which automatically cancels coroutines when the ViewModel is destroyed.
Example of launching a coroutine:
class MyViewModel : ViewModel() {
fun loadData() {
viewModelScope.launch {
// Here you can perform asynchronous operations
val data = repository.getData()
// Update LiveData or state
}
}
}
viewModelScope is a CoroutineScope associated with the lifecycle of the ViewModel, which helps prevent memory leaks and incorrect behavior when the component is destroyed.