首页 > 解决方案 > 在自身内部更新(或创建)流并发出这个、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 设置日期

标签: androidkotlinandroid-roomflow

解决方案


我仍然对您的意思感到困惑,因为您说您知道如何收集流以及如何将列表映射到列表。所以无论如何让我试一试:

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.


推荐阅读