因此,第一次查看协程,我想并行处理数据加载并等待其完成。我一直在环顾四周,看到RunBlocking和Await等,但不确定如何使用它。
我到目前为止
val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }
然后,我想知道/等待这些完成
如果使用结构化并发概念,则无需手动跟踪并发作业。假设您的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()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句