So looking at Coroutines for the first time, I want to process a load of data in parallel and wait for it to finish. I been looking around and seen RunBlocking and Await etc but not sure how to use it.

到目前为止,我已经做到了

val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }

然后我想知道/等待这些完成

推荐答案

如果使用 struct 化并发的概念,则不需要手动跟踪当前作业(job).假设您的processPages函数执行某种阻塞IO,您可以将代码封装到以下挂起函数中,该函数在为此类工作设计的IO调度程序中执行您的代码:

suspend fun processAllPages() = withContext(Dispatchers.IO) { 
    // withContext waits for all children coroutines 
    launch { processPages(urls, collection) }
    launch { processPages(urls, collection2) }
    launch { processPages(urls, collection3) }
}

现在,如果应用程序的最顶层函数还不是挂起函数,则可以使用runBlocking调用processAllPages:

runBlocking {
    processAllPages()
}

Kotlin相关问答推荐

Android前台服务 list —Altbeacon

如何在使用Kotlin Coroutines时检测和记录何时出现背压

使函数同时挂起和取消挂起

房间数据库操作中的协程取消

Kotlin 函数名后面的大括号是什么意思?

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

为什么我的通用Kotlin函数中的这个转换未经判断?

你怎么知道什么时候需要 yield()?

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

在 kotlin 中写入 parcer 可空值

Kotlin 解构超过五个组件

kotlin:扩展方法和空接收器

Kotlin默认使用哪种排序?

如果 Maybe 完成,则从其他来源将 Maybe 转换为 Single

Kotlin 的类型具体化使哪些在 Java 或 Scala 中无法实现的成为可能?

类型不匹配推断类型为单位,但应为空

如何使用mockk库模拟android上下文

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

有没有办法在Kotlin中设置一个私有常量

Dagger 2 androidx fragment不兼容类型