使用协程API获取实体 [英] Obtain entity using coroutines api

查看:106
本文介绍了使用协程API获取实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

coroutines与LiveData一起使用的最佳方法是使用Room从数据库中选择一些数据.

What is the best way to use coroutines with LiveData for selecting some data from database using Room.

这是我的Dao班,选择被暂停

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
}

在视图模型类中,我用viewModelScope加载用户.

Inside of View Model class I load user with viewModelScope.

获取用户实体是否正确?

fun load(userId: Long, block: (User?) -> Unit) = viewModelScope.launch {
    block(database.load(userId))
}

开发人员android 提到

val user: LiveData<User> = liveData {
    val data = database.loadUser() // loadUser is a suspend function.
    emit(data)
}

这段代码不起作用

推荐答案

您的房间必须返回LiveData.

Your Room must return LiveData.

改为使用:

@Dao
interface UserDao {

    @Query("SELECT * from user_table WHERE id =:id")
    fun getUser(id: Long): LiveData<User>
}

这篇关于使用协程API获取实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆