android - 在自身内部更新(或创建)流并发出这个、Room、Flow、MVVM
问题描述
我一直在创建一个短信应用程序。我有一个存储在Room
数据库中的对话列表为ConversationEntity
.
这是我的查询:
@Query("SELECT * FROM conversation_entity ORDER BY timestamp DESC")
fun getAllConversations(): Flow<List<ConversationEntity>>
我想在我的存储库类中从这个查询中观察(收集)数据,但我必须将它映射到List<Conversation>
. 我知道如何收集这些数据,我知道映射List<ConversationEntity>
到List<Conversation>
. 但我不知道我应该如何发出对话列表?
我尝试过从第一个流中发出第二个流,或者使用 MutableStateFlow 并通过 .value 设置日期
解决方案
我仍然对您的意思感到困惑,因为您说您知道如何收集流以及如何将列表映射到列表。所以无论如何让我试一试:
class DAO {
@Query("SELECT * FROM conversation_entity ORDER BY timestamp DESC")
fun getAllConversations(): Flow<List<ConversationEntity>>
}
class Repository(private val dao: Dao) {
fun getConversations(): Flow<List<Converstaion>> {
// this maps every emitted element of the flow
return dao.getAllConversations.map { list: List<ConversationEntity> ->
// and this maps every element in the list
list.map { conversationEntity ->
conversationEntity.mapToConversation()
}
}
}
}
class ConversationMapper {
// Maps ConversationEntity to Conversation
fun ConversationEntity.mapToConversation(): Conversation {
// I have no idea of the fields, so you have to implement this mapping function yourself.
return Converation(...)
}
}
就是这样。以下是如何在 ViewModel 中使用它:
class YourViewModel : ViewModel(private val repository: Repository) {
val converstationLiveData: LiveData = repository.getConversations().toLiveData()
}
Hope that helps you. But if this is still not what you meant, then please update your question accordingly.
推荐阅读
- python - Plotly:如何使用 MULTIPLE 下拉菜单选择图形源?
- matlab - Rounding up to the nearest tenth
- ios - 在 iOS 模拟器上运行 Flutter 应用失败
- java - 在 Java Spring 中将大型 PDF 添加到 zip 文件时出现状态 500 错误
- django - 记录对 Django 模型字段的访问?
- python - 我需要有关 python fpdf 的帮助
- visual-studio-code - “无法解析您的 shell 环境”
- reactjs - 刷新页面时如何获取带有自定义消息的警报/确认对话框
- powershell - Powershell 重定向脚本输出
- r - Rstudio闪亮的应用程序在RSconnect上很慢,但在IDE上很快