I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have
Use Kotlin coroutines with Architecture components.
You can use the liveData
builder function to call a suspend
function, serving the result as a LiveData
object.
val user: LiveData = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
You can also emit multiple values from the block. Each emit()
call suspends the execution of the block until the LiveData
value is set on the main thread.
val user: LiveData = liveData {
emit(Result.loading())
try {
emit(Result.success(fetchUser()))
} catch(ioException: Exception) {
emit(Result.error(ioException))
}
}
In your gradle config, use androidx.lifecycle:lifecycle-livedata-ktx:2.2.0
or higher.
There is also an article about it.
Update: Also it's possible to change LiveData
in the Dao
interface
. You need to add the suspend
keyword to the function:
@Query("SELECT * FROM the_table")
suspend fun getAll(): List
and in the ViewModel
you need to get it asynchronously like that:
viewModelScope.launch(Dispatchers.IO) {
allData = dao.getAll()
// It's also possible to sync other data here
}