Home > Software design >  In android flow room, How to monitor a List of Flow
In android flow room, How to monitor a List of Flow

Time:10-22

Helloo,

----DAO---
@Transaction
@Query("select * from expenses where date= :date")
suspend fun getExpenseWithTagByDate(date: LocalDate): Flow<List<ExpenseWithTag>>

I have a dao code like below. BUT if I need query two days or more, How can I do it?

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)

then

getEnpenseWithTagByMonth(dates).asLiveData()

final i get a type, and it's very terrible:

ArrayList<Flow<List<ExpenseWithTag>>>>>

, o(╥﹏╥)o

How I can write the code with Concise and efficient

CodePudding user response:

To answer your question

if I need query two days or more, How can I do it?

You could use an in query, and then group them.

@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
    }
}
  • Related