Kotlin 如何从房间DB流中获取第一个元素?

Kotlin 如何从房间DB流中获取第一个元素?,kotlin,android-room,coroutine,Kotlin,Android Room,Coroutine,我的存储库中有这样一个函数 fun getSelfReportMetaById(cardId: String): Flow<SelfReportMeta?> { return selfReportMetaDao.getById(cardId) .map { it.map { entity -> entity.toSelfReportMeta() } } .map {

我的存储库中有这样一个函数

fun getSelfReportMetaById(cardId: String): Flow<SelfReportMeta?> {
        return selfReportMetaDao.getById(cardId)
                .map { it.map { entity -> entity.toSelfReportMeta() } }
                .map {
                    it.firstOrNull()
                }
    }
有什么问题吗?问题是,当这个函数运行时,else{}块将基本上连续运行,直到我转到下一个视图。我之所以知道这一点,是因为updateSelfReportMeta()有一个递增操作(++),并且整数值不断递增。我只希望它发生一次。

您可以使用获取流发出的第一个值,然后终止流

您的代码将更改为

viewModelScope.launch {
    val userCard = userRepository.getSelfReportMetaById(cardId).first()
    if (userCard == null) {
        userRepository.insertSelfReportMeta(createNewSelfReportMeta(cardId))
    } else {
        userRepository.insertSelfReportMeta(updateSelfReportMeta(userCard))
    }
}


而不是返回一个空值流,您可以考虑拥有<代码>暂停乐趣GeSelfRelpTeMaByID(CARDID:String):SelfRetryMeta?< /Cord>返回单个值。
viewModelScope.launch {
    val userCard = userRepository.getSelfReportMetaById(cardId).first()
    if (userCard == null) {
        userRepository.insertSelfReportMeta(createNewSelfReportMeta(cardId))
    } else {
        userRepository.insertSelfReportMeta(updateSelfReportMeta(userCard))
    }
}