使用以下代码时出现编译错误:

Suspension functions can be called only within coroutine body

有人能给我解释一下为什么吗?我需要做什么才能使它工作(不使用@Transaction注释)?

override suspend fun replaceAccounts(newAccounts: List<Account>) {
    database.runInTransaction {
        database.accountDao().deleteAllAccounts() // I have the error on this line
        database.accountDao().insertAccounts(newAccounts) // Here too
    }
}

@Dao
abstract class AccountDao : BaseDao<AccountEntity> {

    @Query("DELETE FROM Account")
    abstract suspend fun deleteAllAccounts()

}

Thanks in advance for your help

推荐答案

For suspend functions you should use withTransaction instead of runInTransaction

Kotlin相关问答推荐

Groovy Gradle文件的Kotlin类似功能

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

Kotlin中反射中Int到可空Double的隐式转换失败

返回 kotlin 中的标签和 lambda 表达式

Jetpack Compose:当状态从另一个活动改变时强制重组

正则表达式 FindAll 不打印结果 Kotlin

Kotlin 中获取类简单名称的最佳实践

Kotlin 可打包类抛出 ClassNotFoundException

如何使用 Android CameraX 自动对焦

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

从代码块执行和返回(在 Elvis 运算符之后)

将 @Component.Builder 与构造函数参数一起使用

如何捕获传递给模拟函数的参数并返回它?

用Gradle Kotlin DSL构建源jar?

将字符串编码为Kotlin中的UTF-8

lateinit 的 isInitialized 属性在伴随对象中不起作用

Kotlin 对象 vs 伴生对象(companion-object) vs 包作用域(package scoped)方法

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte

如何修复未解析的参考生命周期范围?

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?