Obtain entity using coroutines api

梦想与她 提交于 2020-05-16 08:56:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!