Reputation: 2119
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>>
Upvotes: 2
Views: 698
Reputation: 8315
Small add on to philip's answer, In your particular case you can replace the lambda with a callable reference to make the code more concise. this can be done as
.mapIterable(Transaction::asDomainModel)
Upvotes: 3
Reputation: 87605
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()
}
}
Upvotes: 2