使用协程如何传递结果? [英] How to pass result as it comes using coroutines?

查看:76
本文介绍了使用协程如何传递结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有回购清单.我想遍历所有这些.当每个回购都返回结果时,我想将其继续传递.

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")

在上述情况下,它等待每个回购返回结果.它依次填充resultsrepo1的结果和repo2的结果.如果repo1repo2花费更多的时间来返回结果,即使我们有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.

这篇关于使用协程如何传递结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆