首页 > 解决方案 > 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在基类中以某种方式定义原始查询?

标签: androidandroid-room

解决方案


推荐阅读