Search code examples
androidandroid-roomkotlin-coroutineskotlin-flow

In android flow + room, How to monitor a List of Flow


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()

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

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

How I can write the code with Concise and efficient


Solution

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