假设我有回购清单.我想遍历所有这些.当每个回购都返回结果时,我想将其继续传递.
Let's say I have list of repos. I want to iterate through all of them. As each repo returns with result, I wanted to pass it on.
val repos = listOf(repo1, repo2, repo3) val deferredItems = mutableListOf<Deferred<List<result>>>() repos.forEach { repo -> deferredItems.add(async { getResult(repo) }) } val results = mutableListOf<Any>() deferredItems.forEach { deferredItem -> results.add(deferredItem.await()) } println("results :: $results")在上述情况下,它等待每个回购返回结果.它依次填充results,repo1的结果和repo2的结果.如果repo1比repo2花费更多的时间来返回结果,即使我们有repo2的结果,我们也将等待repo1的结果.
In the above case, It waits for each repo to return result. It fills the results in sequence, result of repo1 followed by result of repo2. If repo1 takes more time than repo2 to return result, we will be waiting for repo1's result even though we have result for repo2.
一旦得到结果,是否有任何方法可以传递repo2的结果?
Is there any way to pass the result of repo2 as soon as we have the result?
推荐答案Flow API几乎直接支持此功能:
The Flow API supports this almost directly:
repos.asFlow() .flatMapMerge { flow { emit(getResult(it)) } } .collect { println(it) }flatMapMerge首先收集从您传递给它的lambda中出来的所有Flow,然后同时收集它们并将它们完成后立即发送到下游.
flatMapMerge first collects all the Flows that come out of the lambda you pass to it and then concurrently collects those and sends them into the downstream as soon as any of them completes.
更多推荐
使用协程如何传递结果?
发布评论