Sobes.tech
Middle — Middle+

How to implement asynchronous operations using coroutines in ViewModel architecture?

sobes.tech AI

Answer from AI

To implement asynchronous operations in ViewModel using coroutines, viewModelScope is typically used, which automatically cancels coroutines when the ViewModel is destroyed.

Example:

class MyViewModel : ViewModel() {
    fun loadData() {
        viewModelScope.launch {
            val data = fetchDataFromNetwork() // suspend function
            // update UI via LiveData or StateFlow
        }
    }
}

Here, launch starts a coroutine in the ViewModel's context, allowing long-running operations without blocking the main thread. This ensures safe and efficient management of asynchronous tasks within the MVVM architecture.