Android Observable 查询在添加暂停词后不起作用
Android Observable Queries not working after adding suspend word
我正在尝试从 LiveData
迁移到 Kotlin Flow
。现在我正在做一个在 Room
.
有离线支持的项目
我正在查看文档,并设法使用 Flow
在协程中编写了一个可观察的查询。 (参见:here)
我现在面临的问题是,每当我在 DAO
class 中添加 suspend 关键字并尝试 运行 项目时,它都会失败并出现以下错误:
error: Not sure how to convert a Cursor to this method's return type (kotlinx.coroutines.flow.Flow<MyModel>).
有问题的代码:
@Transaction
@Query("SELECT * FROM table WHERE status = :status LIMIT 1")
suspend fun getWithSpecificStatus(status: String): Flow<MyModel?>
我这样调用代码:
val modelLiveData: LiveData<MyModel?> = liveData(Dispatchers.IO) {
val result = databaseService.getWithSpecificStatus(Enum.IN_PROGRESS.status).first()
result?.let {
emit(it)
}
}
我试图让事情变得简单。为什么我的代码失败了?
您可以直接将 modelLiveData 的值初始化为:
val modelLiveData=databaseService.
getWithSpecificStatus(Enum.IN_PROGRESS.status).first()
.asLiveData()
您使用了 Flow,因此 asLiveData()
用于将其转换为 LiveData
另外建议,你不应该使用 suspend 关键字,因为当你返回 Flow 时,Room 会自动异步执行此操作。你只需要消耗流量即可。
我正在尝试从 LiveData
迁移到 Kotlin Flow
。现在我正在做一个在 Room
.
我正在查看文档,并设法使用 Flow
在协程中编写了一个可观察的查询。 (参见:here)
我现在面临的问题是,每当我在 DAO
class 中添加 suspend 关键字并尝试 运行 项目时,它都会失败并出现以下错误:
error: Not sure how to convert a Cursor to this method's return type (kotlinx.coroutines.flow.Flow<MyModel>).
有问题的代码:
@Transaction
@Query("SELECT * FROM table WHERE status = :status LIMIT 1")
suspend fun getWithSpecificStatus(status: String): Flow<MyModel?>
我这样调用代码:
val modelLiveData: LiveData<MyModel?> = liveData(Dispatchers.IO) {
val result = databaseService.getWithSpecificStatus(Enum.IN_PROGRESS.status).first()
result?.let {
emit(it)
}
}
我试图让事情变得简单。为什么我的代码失败了?
您可以直接将 modelLiveData 的值初始化为:
val modelLiveData=databaseService.
getWithSpecificStatus(Enum.IN_PROGRESS.status).first()
.asLiveData()
您使用了 Flow,因此 asLiveData()
用于将其转换为 LiveData
另外建议,你不应该使用 suspend 关键字,因为当你返回 Flow 时,Room 会自动异步执行此操作。你只需要消耗流量即可。