Kotlin 协程是否有 asyncAll and/or awaitAll 运算符?
Is there asyncAll and/or awaitAll operators for Kotlin coroutines?
我有一个集合,我想在 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()
我可能可以用扩展函数来实现它。我只是想知道是否有更惯用的方法来做到这一点。
EDIT: 我发现 awaitAll 已经存在了。现在,我只需要一个 asyncAll。
list.map { async { callRemoteService(it) } }.awaitAll().forEach { println(it) }
EDIT2:
我写了我的 asyncAll 实现:
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()
现在,我只是想知道它是否已经存在:)
编辑3:
想想看,这样还可以更好看:
list.asyncAll { callRemoteService(it) }.awaitAll()
我只是在执行时遇到了问题。因为我这里已经有一个可迭代的接收器,所以我不确定如何通过协程范围:
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 中对它的所有项目异步执行一些操作。
我可以通过两个地图操作轻松做到这一点:
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()
我可能可以用扩展函数来实现它。我只是想知道是否有更惯用的方法来做到这一点。
EDIT: 我发现 awaitAll 已经存在了。现在,我只需要一个 asyncAll。
list.map { async { callRemoteService(it) } }.awaitAll().forEach { println(it) }
EDIT2: 我写了我的 asyncAll 实现:
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()
现在,我只是想知道它是否已经存在:)
编辑3: 想想看,这样还可以更好看:
list.asyncAll { callRemoteService(it) }.awaitAll()
我只是在执行时遇到了问题。因为我这里已经有一个可迭代的接收器,所以我不确定如何通过协程范围:
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
。