首页 文章

使用Kotlin协程时,Room dao类出错

提问于
浏览
6

我正在尝试使用kotlin协同程序通过描述的方法访问房间数据库here,添加了插件和依赖项,并在gradle中启用了kotlin协同程序 .

gradle 文件中:

kotlin {
    experimental {
        coroutines 'enable'
    }
}
dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.21" ...}

所以我为dao类中的所有方法添加了 suspend 关键字,如下所示:

dao class

@Query("select * from myevent")
suspend fun all(): List<MyEvent>

@Delete
suspend fun deleteEvent(event: MyEvent)
...

并构建,然后得到这些错误

error

e: C:\Users\projectpath\app\build\tmp\kapt3\stubs\debug\com\robyn\myapp\data\source\local\EventsDao.java:39: error: Deletion methods must either return void or return int (the number of deleted rows). public abstract java.lang.Object deleteEventById(@org.jetbrains.annotations.NotNull() ^ e: C:\Users\projectpath\app\build\tmp\kapt3\stubs\debug\com\robyn\myapp\data\source\local\EventsDao.java:41: error: Query method parameters should either be a type that can be converted into a database column or a List / Array that contains such type. You can consider adding a Type Adapter for this. kotlin.coroutines.experimental.Continuation<? super kotlin.Unit> p1);

错误链接导航到 auto generated dao类 . 此类中生成的方法现在每个都有一个此类型的附加参数 Continuation ,如下所示:

auto generated dao class

@org.jetbrains.annotations.Nullable()
@android.arch.persistence.room.Delete()
public abstract java.lang.Object deleteAllEvents(@org.jetbrains.annotations.NotNull() // error indicates at this line
java.util.List<com.robyn.myapp.data.MyEvent> events, @org.jetbrains.annotations.NotNull()
kotlin.coroutines.experimental.Continuation<? super kotlin.Unit> p1); // error indicates at this line
...

我尝试删除生成的dao类并重建以重新入侵它,仍然会得到这些错误 . 我认为不使用 lauch{} 方法但使用 suspend 关键字,因为代码中有很多地方可以查询db .

我怎样才能解决这个问题?

1 回答

  • 4

    您不能将 suspend 方法用于DAO . 挂起在编译时处理的函数,编译器更改此函数的签名(不同的返回类型,状态机回调的附加参数),使其成为非阻塞函数 .

    房间等待特定方法签名生成代码 . 因此,直到Room不直接支持协同程序,您不能使用DAO的暂停功能 .

    目前,您有这样的解决方法:

    • 如果DAO方法返回值,使用RxJava或LiveData获取它并使用coroutine adapter for RxJava或为LiveData编写自己的(不知道现有的)

    • 用自己的线程池包装同步DAO方法调用coroutine(因为这样的调用将被阻塞) .

    但是如果可能的话,总是更喜欢选项1,因为Room已经提供了非阻塞API,只需使用协程适配器允许在没有回调的情况下使用这个API和协同程序

    Room 2.1.0-alpha03 开始,DAO方法现在可以是 suspend 函数 . 专门注释为@Insert,@ Update或@Delete的Dao方法可以是挂起函数 . 注释为@Query的插入,更新和删除是not yet supported,尽管是普通查询 . 有关详细信息,请参阅:Architecture Components Release NotesFeature Request .

相关问题