问题
What is the best way to use coroutines
with LiveData for selecting some data from database using Room
.
This is My Dao class with suspended selection
@Dao
interface UserDao {
@Query("SELECT * from user_table WHERE id =:id")
suspend fun getUser(id: Long): User
}
Inside of View Model class I load user with viewModelScope
.
Does it correct way to obtain user entity ?
fun load(userId: Long, block: (User?) -> Unit) = viewModelScope.launch {
block(database.load(userId))
}
According developer android mentioned
val user: LiveData<User> = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
This chunk of code does not work
回答1:
Your Room must return LiveData.
Use instead:
@Dao
interface UserDao {
@Query("SELECT * from user_table WHERE id =:id")
fun getUser(id: Long): LiveData<User>
}
来源:https://stackoverflow.com/questions/59859988/obtain-entity-using-coroutines-api