android - Room - 通用基类中的查询(尤其是流查询)
问题描述
在房间里,似乎不可能在具有基于变量的数据或提供的类的泛型类中使用基于注释的设置 - 结果是没有解决方法来Flow
在抽象泛型基类中定义查询。
真的要试试吗?
示例 1 - 可以解决
定义一个查询,其中包含一个由类变量定义的表名
@Dao
abstract class BaseDao<Item : IItem, ItemWithRef> {
abstract val tableName: String
// DOES NOT WORK - because table name is not compile-time constant
@Transaction
@Query("select * from ${tableName}")
abstract suspend fun loadAll(): List<ItemWithRef>
// SOLUTION
private val rawQueryLoadAll
get() = "SELECT * FROM $tableName"
@Transaction
@RawQuery
protected abstract suspend fun loadAll(query: SimpleSQLiteQuery): List<ItemWithRef>
suspend fun loadAll(): List<ItemWithRef> = loadAll(queryLoadAll)
}
示例 2 - 无法解决?
定义包含由类变量定义的表名的流查询
这里的问题是,@RawQuery
需要知道查询类——这也能以某种方式解决吗?
@Dao
abstract class BaseDao<Item : IItem, ItemWithRef> {
abstract val tableName: String
// all 3 possibilities DO NOT WORK
// - because `@RawQuery` needs to know that it handles `ItemWithRef::class`
// - because the table name is not constant
// DOES NOT WORK
@Transaction
@Query("select * from ${tableName}")
abstract suspend fun flowAll(): Flow<List<ItemWithRef>>
// DOES NOT WORK
@Transaction
@RawQuery
protected abstract fun flowAll(query: SimpleSQLiteQuery): Flow<List<ItemWithRef>>
fun flowAll(): Flow<List<ItemWithRef>> = flowAll(queryLoadAll)
// DOES NOT WORK
@Transaction
@RawQuery(observedEntities = arrayOf(ItemWithRef::class))
protected abstract fun flowAll(query: SimpleSQLiteQuery): Flow<List<ItemWithRef>>
fun flowAll(): Flow<List<ItemWithRef>> = flowAll(queryLoadAll)
}
问题
我对示例 1 的解决方法很好,但是是否有任何解决方法也可以Flow
在基类中以某种方式定义原始查询?
解决方案
推荐阅读
- python-3.x - 如何在 Scrapy 中用 tbody 抓取这个 HTML 结构?
- html - 单击按钮时未显示 Ng 容器
- r - 在 R 的列中搜索特定短语的问题 [有史以来的第一个问题]
- arrays - 存储浮点的紧凑方式
- c# - 如何让物体自行移动?
- r - 使用 Photon 的 R 闪亮独立应用程序
- python - 单击空白区域时禁用选择/背景颜色
- python - 如何在服务器中托管的 mongoDB 数据库和远程设备中托管的 SQLite 数据库之间建立备份系统?
- groovy - 如何在响应断言失败时将 JMeter 变量写入文件
- python - Pandas 与许多条件和不一致的数据合并