因此,第一次查看协程,我想并行处理数据加载并等待其完成.我环顾四周,看到RunBlocking和Await等,但不确定如何使用它.
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) }然后我想知道/等待这些完成
I then want to know/wait for these to finish
推荐答案如果您使用结构化并发概念,则无需手动跟踪当前的工作.假设您的processPages函数执行某种阻塞的IO,则可以将代码封装到以下挂起函数中,该函数在为此工作而设计的IO调度程序中执行代码:
You don't need to manually keep track of your cuncurrent jobs if you use the concept of structured concurrency. Assuming that your processPages function performs some kind of blocking IO, you can encapsulate your code into the following suspending function, which executes your code in an IO dispatcher designed for this kind of work:
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:
Now, from if a topmost function of your application is not already a suspending function, then you can use runBlocking to call processAllPages:
runBlocking { processAllPages() }更多推荐
Kotlin协程:等待多个线程完成
发布评论