Sobes.tech
Junior — Middle

Kuidas alustada coroutine'i täitmist ViewModeli raames?

sobes.tech AI

Vastus AI-lt

In Android, viewModelScope is commonly used to launch a coroutine in a ViewModel, which automatically cancels coroutines when the ViewModel is destroyed.

Example of launching a coroutine:

class MyViewModel : ViewModel() {
    fun loadData() {
        viewModelScope.launch {
            // You can perform asynchronous operations here
            val data = repository.getData()
            // Update LiveData or state
        }
    }
}

viewModelScope is a CoroutineScope tied to the lifecycle of the ViewModel, helping to prevent memory leaks and incorrect behavior when the component is destroyed.