返回

android room——Flow 的 collect 函数是 Kotlin 中的块函数吗?

发布时间:2022-05-18 07:51:58 304
# java

我希望通过 Id 列表和 Room 的相关文件删除记录。

当我运行代码A时,我发现文件可以被删除并且记录不能被删除

我发现运行代码 B 时可以删除记录。

Code A 中好像Log.e("My","Fire")没有启动。不知道为什么?

Q1:代码 A 有什么问题?

Q2:collect我使用 Flow 时是否有a block 功能?

Q3: 是fun getByID(id:Int): Flow<RecordEntity?> 好的设计吗?也许应该是fun getByID(id:Int): RecordEntity?。

代码 A

class RecordRepository @Inject constructor(
    private val mRecordDao:RecordDao
) {   
    override fun getByID(id:Int): Flow<MRecord?> =  mRecordDao.getByID(id).map {it?.let{ModelMapper.entityToModel(it) } }
 

    override suspend fun deleteRecord(idList: List) = withContext(Dispatchers.Default) {
        idList.forEach{
            getByID(it).collect {
               it?.let {
                   val filename = it.soundFileName
                   deleteFileOrFolder(filename)
               }
            }
        }
        Log.e("My","Fire")
        mRecordDao.deleteRecord(idList)
    }

}

@Dao
interface  RecordDao {
    @Query("SELECT * FROM record_table where id=:id")
    fun getByID(id:Int): Flow<RecordEntity?> 

    @Query("delete from record_table where id in (:idList)")
    suspend fun deleteRecord(idList: List)
}

代码B

class RecordRepository @Inject constructor(
    private val mRecordDao:RecordDao
) {   
    override fun getByID(id:Int): Flow<MRecord?> =  mRecordDao.getByID(id).map {it?.let{ModelMapper.entityToModel(it) } }


    override suspend fun deleteRecord(idList: List) = withContext(Dispatchers.Default) { 
        mRecordDao.deleteRecord(idList)
    }

}

//The same

新增内容:

致 Arpit Shukla:谢谢!

我发现许多查询示例使用 Code C 返回带有 Room 的 Flow 数据。

我认为 Code D 足够了,而且很简单

我很困惑为什么我需要在房间中使用 Flow,你知道我只想要实体一次,你能告诉我吗?

代码C

@Dao
interface  RecordDao {
    @Query("SELECT * FROM record_table ORDER BY createdDate desc")
    fun listRecord():  Flow<List>
}

代码D

@Dao
interface  RecordDao {
    @Query("SELECT * FROM record_table ORDER BY createdDate desc")
    suspend  fun listRecord(): List
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像