【问题标题】:Using kotlin coroutines with room使用带有房间的 kotlin 协程
【发布时间】:2020-01-04 11:37:27
【问题描述】:

在 2.1 Room 中添加了对协程的支持,但我无法让它工作。它应该像添加依赖项一样简单,但不知何故我忽略了一些东西。

在我的 build.gradle 中,我得到了协程、房间和房间协程的依赖项

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、清理和重建项目。

在我的 Doa 中,我有如下方法

@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的链接,我想看看你是如何使用协程的

标签: android kotlin android-room kotlin-coroutines


【解决方案1】:

您正在混合不同版本的房间库。

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#Declaring dependencies

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

【讨论】:

    猜你喜欢
    • 2019-06-28
    • 2021-11-24
    • 2021-12-17
    • 2019-11-28
    • 2018-05-18
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多