GOOGLE ADS

Donnerstag, 14. April 2022

Wie gebe ich ein Objekt in einer suspendierten Funktion zurück, nachdem ich das Objekt von einem Flow erhalten habe?

Ich frage mich, ob es eine Möglichkeit gibt, auf den Abschluss eines Flows zu warten und das Ergebnis in einer Suspend-Funktion zurückzugeben. transactionRepository.getAll(accountId)gibt einen Fluss von Transaktionen zurück

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-Funktion in meinem Repository definiert:

fun getAll(accountId: Int): Flow<List<DatabaseTransaction>>


Lösung des Problems

Angenommen, Sie möchten nur den ersten Wert, der vom Flow zurückgegeben wird, und es ist ein List<Transaction>, können Sie verwenden first(). Aber ich vermute nur, weil ich nicht weiß, was getAll()zurückkommt, und ich bin nicht vertraut mit 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
}

Keine Kommentare:

Kommentar veröffentlichen

Warum werden SCHED_FIFO-Threads derselben physischen CPU zugewiesen, obwohl CPUs im Leerlauf verfügbar sind?

Lösung des Problems Wenn ich das richtig verstehe, versuchen Sie, SCHED_FIFO mit aktiviertem Hyperthreading ("HT") zu verwenden, ...