是否存在用于Kotlin协程的All和/或Wait All操作符?是否存在、操作、All、Kotlin

由网友(放逐、青春)分享简介:我有一个集合,我想在Kotlin中对其中的所有项异步执行一些操作。我可以通过两个映射操作轻松完成此操作:suspend fun collectionAsync() = coroutineScope {val list = listOf("one", "two", "three")list.map { async { c...

我有一个集合,我想在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"
}
Java或将被Kotlin取代 现在学Kotlin还来得及吗

我想要的是这样的:

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

阅读全文

相关推荐

最新文章