【发布时间】:2021-11-14 21:19:47
【问题描述】:
我对定期调用的函数有这个要求:
1. Get some input
2. Do 8 independent computations based on the input
3. Merge the results from these 8 computations and output the merged result
由于我至少有 8 个处理器,我可以并行执行 8 个独立计算。所以我创建了以下函数:
fun process(in: InputType): ResultType {
runBlocking(Dispatchers.Default) {
val jobs = in.splitToList().map { async { processItem(it) } }
return jobs.awaitAll()
}
}
但是,我在documentation of runBlocking 中读到它是“用于主要功能和测试”。
此函数不是主函数,而是在应用程序的调用层次结构中向下调用,该应用程序不会在其他任何地方使用协程。
如果我不应该使用 runBlocking,我应该使用什么来实现此要求?
【问题讨论】:
-
这可能有助于你理解
runBlockingstackoverflow.com/a/69258652/8110255