Ejemplo de corrutinas en Kotlin
Buscador de recetas en Kotlin usado corrutinas
Efficient Android Development with Kotlin Coroutines: Building a Recipe Finder App
ViewModel
class RecipeViewModel : ViewModel() {
val recipes: LiveData<Result<List<Recipe>>> = liveData(Dispatchers.IO) {
emit(Result.Loading) // Indicate loading state
try {
// Simulate network delay and fetch data
val fetchedRecipes = withContext(Dispatchers.IO) {
delay(2000) // Simulate network delay
FakeDatabase.getAllRecipes() // Fetch recipes
}
emit(Result.Success(fetchedRecipes)) // Emit successful data fetch
} catch (e: Exception) {
// Emit a detailed error state
emit(Result.Error(Exception("Error fetching recipes: ${e.localizedMessage}")))
}
}
}
emit()
In the context of the liveData coroutine builder used in your RecipeViewModel, emit() is a suspending function used to update the value of the LiveData object.
Here is a breakdown of what it does:
1. Sends Data to Observers: When you call emit(value), it sets that value on the LiveData. Any active observers (like your MainActivity) will immediately receive this new value and can update the UI accordingly.
2. Sequential Delivery: Because liveData { … } runs as a coroutine, emit() allows you to send multiple values over time. In the code:
◦ It first emits Result.Loading to show a progress bar.
◦ After the simulated delay, it emits either Result.Success with the data or Result.Error if something went wrong.
3. Thread Safety: It handles the transition between the background thread (where your data is fetched) and the main thread (where the UI is updated).
4. Lifecycle Awareness: The liveData block only executes and emits values when the LiveData has active observers. If the user leaves the screen, the execution pauses and resumes only if they return.
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.