Issue
I am wondering if there's a better way to call a method on an element within a list that is contained in a Flow. Currently i'm doing this but i don't like calling map() twice:
override fun getEarnings(): Flow<List<Transaction>> {
return transactionDao.getEarnings().map {
it.map { transaction -> transaction.asDomainModel() }
}
}
the getEarnings() method defined in the transactionsDao:
@Query("SELECT * FROM transactions WHERE is_income = 1")
fun getEarnings(): Flow<List<DatabaseTransaction>>
Solution
I've created this extension for the same purpose:
inline fun <T, R> Flow<Iterable<T>>.mapIterable(crossinline transform: (T) -> R): Flow<List<R>> =
map { it.map(transform) }
Usage:
fun getEarnings(): Flow<List<Transaction>> {
return transactionDao
.getEarnings()
.mapIterable { transaction ->
transaction.asDomainModel()
}
}
Answered By - Philip Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.