使用协程如何传递结果?

编程入门 行业动态 更新时间:2024-10-27 22:21:42
本文介绍了使用协程如何传递结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

使用协程如何传递结果?

本文发布于:2023-11-23 10:41:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!