Android分页库+房间关系

时间:2020-10-16 22:22:14

标签: android kotlin android-room android-livedata

我所看到的有关分页库的示例都假定您需要一个Livedata<List<T>>,但是该列表位于另一个对象内部的Room关系又如何呢?

我的应用程序中有两个实体:ConversationMessage,它们与此类相关:

data class ConversationWithMessages(
    @Embedded val conversation: Conversation,
    @Relation(
        parentColumn = "conversation_gid",
        entityColumn = "conversationId"
    )
    val messages: List<Message>
)

我从不以LiveData<List<Message>>的形式提取所有消息,而是一次对话(通过其ID)加上其所有子消息。 DAO函数如下所示:

@Transaction
@Query("SELECT * FROM conversations WHERE conversation_gid =:conversationId LIMIT 1")
fun getConversationLiveDataById(conversationId: Long): LiveData<ConversationWithMessages>

我有一个存储库,可以直接从DAO返回LiveData<ConversationWithMessages>

在Viewmodel中,我有一个conversations变量来保存实时数据:

var conversation: LiveData<ConversationWithMessages> = MutableLiveData()
// ...
conversation = conversationRepository.getConversation(conversationId)

在我的片段上,我只是观察了此实时数据以更新适配器:

private val conversationObserver = Observer<ConversationWithMessages> {
    it?.let {
        // it.messages gives me the list I use to update
    }
}

我最初想到在关系数据类上使用PagedList

data class ConversationWithMessages(
    @Embedded val conversation: Conversation,
    @Relation(
        parentColumn = "conversation_gid",
        entityColumn = "conversationId"
    )
    val messages: PagedList<Message>
)

然后返回DataSource的DAO查询如下所示:

@Transaction
@Query("SELECT * FROM conversations WHERE conversation_gid =:conversationId LIMIT 1")
fun getConversationLiveDataById(conversationId: Long): DataSource.Factory<Int, ConversationWithMessages>

但是如何将这个数据源转换为配置了子LiveData<ConversationWithMessages>的{​​{1}}? Google有这个例子,但我看不到如何将其应用于这种情况:

PagedList<Message>

0 个答案:

没有答案