使用 Kotlin 协程与 Room

4

在2.1版本中,Room增加了对协程的支持,但我无法使其工作。只需要添加依赖项,但不知为何我还是漏掉了什么。

在我的build.gradle文件中,我已添加了协程、Room和room-coroutines的依赖项。

dependencies { 
    def room_version = "2.2.0-beta01"
    // Room components
    implementation "android.arch.persistence.room:runtime:$room_version"
    kapt "android.arch.persistence.room:compiler:$room_version"
    implementation "androidx.room:room-ktx:$room_version"
    androidTestImplementation "android.arch.persistence.room:testing:$room_version"
    def coroutines_version = "1.1.1"
    // Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
}

我已经尝试过重新同步Gradle、清理和重建项目。

在我的DAO中,我有以下方法:

@Dao
interface PlanDao {
    @Insert
    suspend fun insertVerPlan(verPlan: SqlVerPlan)
}

尝试构建项目时,Room不知道如何处理悬挂函数,导致出现以下错误:
error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    kotlin.coroutines.Continuation<? super kotlin.Unit> p1);
                                                        ^

error: Methods annotated with @Insert can return either void, long, Long, long[], Long[] or List<Long>.
    public abstract java.lang.Object insertVerPlan(@org.jetbrains.annotations.NotNull()
                                     ^

我真的不知道自己缺少什么,而且自从新的Room版本发布以来,我也找不到有相同问题的人。


你好,请不要附加Git链接,我想看看你如何使用协程工作。 - danilshik
1个回答

4

您正在混用不同版本的room库。

android.arch.persistence.room:runtime 应该改为 androidx.room:room-runtime

android.arch.persistence.room:compiler 应该改为 androidx.room:room-compiler

android.arch.persistence.room:testing 应该改为 androidx.room:room-testing

参考 Room#声明依赖关系

由于您正在使用编译器的旧坐标,它不知道suspend支持。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接