使用Deferred< ...>在Kotlin协程的DAO房间中 [英] Using Deferred<...> in Room DAO with Kotlin Coroutines

查看:366
本文介绍了使用Deferred< ...>在Kotlin协程的DAO房间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将协程与Android项目中的Room数据库一起使用.我几乎没有在线找到任何文档,我想知道是否有可能在这些方法中返回Deferred<>类型.像这样:

I'm trying to use Coroutines with a Room database in an Android project. I've found almost no documentation online, and I'm wondering if it is possible to return Deferred<> types in those methods. Something like this:

@Dao
interface MyObjectDAO {

@Query("SELECT * FROM myObject WHERE id_myObject = :idMyObject")
suspend fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject>
}

我已经尝试过了,在编译时得到了Not sure how to convert a Cursor to this method's return type.

I've tried this and I get Not sure how to convert a Cursor to this method's return type at compile time.

我的依赖项是:

kapt 'androidx.room:room-compiler:2.1.0-alpha04'
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
implementation 'androidx.room:room-coroutines:2.1.0-alpha04'

推荐答案

您的问题在于,您正在混合suspend ing转换器和Deferred转换器.使用其中之一,您的代码将按预期工作.

Your issue lies in that you're mixing the suspending converter and the Deferred converter. Use one or the other and your code will work as intended.

  • fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject>-如果您需要与Java代码接口/兼容,这是最佳选择,因为它不需要代码转换即可真正起作用.
  • suspend fun readMyObjectAsync(idMyObject: Int): MyObject-如果您使用的是纯Kotlin,则可以更好地控制调用它的上下文.
  • fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject> - Best choice if you need to interface/be compatible with java code, since it doesn't require code transformations to actually function.
  • suspend fun readMyObjectAsync(idMyObject: Int): MyObject - If you're operating on pure kotlin this will allow better control through the context it is called in.

这篇关于使用Deferred&lt; ...&gt;在Kotlin协程的DAO房间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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