首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Kotlin协程:等待多个线程完成

Kotlin协程:等待多个线程完成
EN

Stack Overflow用户
提问于 2019-02-25 00:48:45
回答 3查看 17.4K关注 0票数 14

因此,第一次查看协程时,我希望并行处理大量数据,并等待其完成。我环顾四周,看到了RunBlocking和Await等,但不确定如何使用它。

到目前为止我已经

代码语言:javascript
运行
复制
val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }

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

EN

Stack Overflow用户

发布于 2019-02-25 02:21:43

您可以使用async构建器函数并行处理大量数据:

代码语言:javascript
运行
复制
class Presenter {
    private var job: Job = Job()
    private var scope = CoroutineScope(Dispatchers.Main + job) // creating the scope to run the coroutine. It consists of Dispatchers.Main (coroutine will run in the Main context) and job to handle the cancellation of the coroutine.

    fun runInParallel() {
        scope.launch { // launch a coroutine
            // runs in parallel
            val deferredList = listOf(
                    scope.asyncIO { processPages(urls, collection) },
                    scope.asyncIO { processPages(urls, collection2) },
                    scope.asyncIO { processPages(urls, collection3) }
            )

            deferredList.awaitAll() // wait for all data to be processed without blocking the UI thread

            // do some stuff after data has been processed, for example update UI
        }
    }

    private fun processPages(...) {...}

    fun cancel() {
        job.cancel() // invoke it to cancel the job when you don't need it to execute. For example when UI changed and you don't need to process data
    }
}

扩展函数asyncIO

代码语言:javascript
运行
复制
fun <T> CoroutineScope.asyncIO(ioFun: () -> T) = async(Dispatchers.IO) { ioFun() } // CoroutineDispatcher - runs and schedules coroutines

GlobalScope.launch is not recommended to use,除非您希望协程在整个应用程序生命周期中运行,而不是过早取消。

编辑:就像罗曼·伊丽莎白提到的那样,你可以试着不使用awaitAll()函数,除非你想在处理完所有数据后立即更新UI或做其他事情。

票数 13
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54854187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档