Issue
I'm wondering if there's a way to wait for a flow to be complete and return the result inside a suspend function. transactionRepository.getAll(accountId)
returns a flow of transactions
override suspend fun getAccount(accountId: Int): Account {
val account = Account(accountRepository.get(accountId))
transactionRepository.getAll(accountId).mapIterable {
val transaction = Transaction(it)
val category = Category(categoryRepository.get(it.categoryId))
transaction.category = category
transaction.account = account
return@mapIterable transaction
}.collect {
account.transactions = it
}
//TODO: How can i return an account after the flow has been executed?
}
getAll function defined in my repository:
fun getAll(accountId: Int): Flow<List<DatabaseTransaction>>
Solution
Assuming you want just the first value returned by the flow, and it's a List<Transaction>
, you can use first()
. But I'm only guessing because I don't know what getAll()
returns and I'm not familiar with mapIterable
.
override suspend fun getAccount(accountId: Int): Account {
val account = Account(accountRepository.get(accountId))
val transactionsFlow: Flow<List<Transaction>> = transactionRepository.getAll(accountId).mapIterable {
val transaction = Transaction(it)
val category = Category(categoryRepository.get(it.categoryId))
transaction.category = category
transaction.account = account
return@mapIterable transaction
}
account.transactions = transactionsFlow.first()
return account
}
Answered By - Tenfour04
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.