gpt4 book ai didi

kotlin - Kotlin:在列表 “in parallel”上应用暂停功能?

转载 作者:行者123 更新时间:2023-12-02 13:27:47 25 4
gpt4 key购买 nike

如果我有一个List<A>和一个函数suspend (A) -> B,如何在列表上并行应用此函数?

最佳答案

您可以在CoroutineScope上创建扩展功能,遍历列表的每个元素并为每个元素启动协程。这样,列表中的元素将被并行处理。一些代码片段:

fun CoroutineScope.processListInParallel(list: List<A>): List<Deferred<B>> = list.map {
async { // launch a coroutine
processA(it)
}
}

GlobalScope.launch {
val list = listOf(A("name1"), A("name2"), A("name3"))
val deferredList = processListInParallel(list)
val results: List<B> = deferredList.awaitAll() // wait for all items to be processed
}

suspend fun processA(a: A): B {
delay(1000) // emulate suspension
return B("Result ${a.name}")
}

data class A(val name: String) {}
data class B(val name: String) {}
注意:此处以 GlobalScope为例,使用时高度为 discouraged,应用程序代码通常应使用应用程序定义的 CoroutineScope

关于kotlin - Kotlin:在列表 “in parallel”上应用暂停功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63216511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com