Reputation: 14937
I have a transaction repository from which I can get a Flow<List<Transaction>>
.
Based on this data, I need to create a Flow<List<Source?>>
.
The transaction
has sourceId
which can be passed to sourceRepository.getSource()
which returns a source if it exists or else it returns null
.
ViewModel code
var transactions: Flow<List<Transaction>> = transactionRepository.transactions
var sourceList: Flow<List<Source?>> = flow {
transactions.map {
it.map { transaction ->
if (transaction.sourceId != null) {
sourceRepository.getSource(transaction.sourceId)
} else {
null
}
}
}.collect {
emit(it)
}
}
Is there any way to change the map
of map
and make this code less?
Upvotes: 3
Views: 6119
Reputation: 10523
I don't think you can avoid map
s here. What you can avoid is the extra flow
builder.
val transactions: Flow<List<Transaction>> = transactionRepository.transactions
val sourceList: Flow<List<Source?>> =
transactions.map { list ->
list.map { transaction ->
transaction.sourceId?.let { sourceRepository.getSource(it) }
}
}
Also, prefer val
s over var
s.
Upvotes: 6