Hello,
----DAO---
@Transaction
@Query("select * from expenses where date= :date")
suspend fun getExpenseWithTagByDate(date: LocalDate): Flow<List<ExpenseWithTag>>
我有一个如下的dao代码但如果我需要查询两天或更长时间,我该怎么做
fun getEnpenseWithTagByMonth(dates: List<LocalDate>) =
flow {
val lists = arrayListOf<Flow<List<ExpenseWithTag>>>()
dates.forEach {
val expenses = expenseDao.getExpenseWithTagByDate(it)
lists.add(expenses)
}
emit(lists)
}.flowOn(Dispatchers.IO)
然后
getEnpenseWithTagByMonth(dates).asLiveData()
最后我得到了一个类型,它非常可怕:
ArrayList<Flow<List<ExpenseWithTag>>>>>
如何使用简洁高效的编写代码
回答您的问题
如果我需要查询两天或更长时间,我该怎么做?
您可以使用in
查询,然后对它们进行分组。
@Query("select * from expenses where date IN (:dates)")
suspend fun getExpenseWithTagByDate(dates: List<LocalDate>): Flow<List<ExpenseWithTag>>
fun getEnpenseWithTagByMonth(dates: List<LocalDate>): Flow<List<List<ExpenseWithTag>>> {
return expenseDao.getExpenseWithTagByDate(dates).map { expenses ->
expenses.groupBy{ expense -> expense.date }.values
}
}