是否存在用于Kotlin协程的All和/或Wait All操作符? [英] Is there asyncAll and/or awaitAll operators for Kotlin coroutines?

查看:0
本文介绍了是否存在用于Kotlin协程的All和/或Wait All操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,我想在Kotlin中对其中的所有项异步执行一些操作。

我可以通过两个映射操作轻松完成此操作:

suspend fun collectionAsync() = coroutineScope {

    val list = listOf("one", "two", "three")

    list.map { async { callRemoteService(it) } }.map { it.await() }.forEach { println(it) }
}

suspend fun callRemoteService(input: String): String
{
    delay(1000)
    return "response for $input"
}

我想要的是这样的:

asyncAll(list, ::callRemoteService).awaitAll()

我可能可以用扩展函数来实现它。我只是想知道有没有更惯用的方式。

编辑:我发现waitAll已经存在。现在,我只需要一个All。

list.map { async { callRemoteService(it) } }.awaitAll().forEach { println(it) }

EDIT2: 我编写了我的All异步实现:

fun <T, V> CoroutineScope.asyncAll(
    items: Iterable<T>,
    function: suspend (T) -> V
): List<Deferred<V>>
{
    return items.map { async { function.invoke(it) } }
}

所以现在我有了这个,看起来很不错:

asyncAll(list) { callRemoteService(it) }.awaitAll()

现在,我只是想知道它是否是已经存在的东西:)

EDIT3: 仔细想想,这甚至可能看起来更好:

list.asyncAll { callRemoteService(it) }.awaitAll()

我只是在实现上遇到了问题。因为我这里已经有了一个可迭代的接收器,所以我不确定如何才能传递Couroute作用域:

fun <T, V> Iterable<T>.asyncAll(
    function: (T) -> V
): List<Deferred<V>>
{
    return this.map { async { function.invoke(it) } }
}

推荐答案

终于得到了我想要的解决方案。我需要此扩展函数:

suspend fun <T, V> Iterable<T>.asyncAll(coroutine: suspend (T) -> V): Iterable<V> = coroutineScope {
    this@asyncAll.map { async { coroutine(it) } }.awaitAll()
}

我可以这样使用它:

list.asyncAll { callRemoteService(it) }.forEach { println(it) }

我对命名不太确定。也可以是asyncMap

这篇关于是否存在用于Kotlin协程的All和/或Wait All操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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