Coroutines in Kotlin provide a powerful way to handle asynchronous programming, making it easier to write non-blocking code. They allow you to perform long-running tasks, such as network calls or database operations, without freezing the user interface. By using the `viewModelScope` in your ViewModel, you can launch coroutines that are automatically canceled when the ViewModel is cleared, ensuring efficient resource management.
class MyViewModel : ViewModel() {
private val _data = MutableLiveData()
val data: LiveData get() = _data
fun fetchData() {
viewModelScope.launch {
// Simulating a long-running task such as a network call
val result = withContext(Dispatchers.IO) {
// Replace with actual network call
delay(2000) // Simulating a delay
"Fetched Data"
}
_data.value = result
}
}
}