Abhimanyu
Abhimanyu

Reputation: 14937

Kotlin Map Flow of list of items

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

Answers (1)

Arpit Shukla
Arpit Shukla

Reputation: 10523

I don't think you can avoid maps 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 vals over vars.

Upvotes: 6

Related Questions