因此,第一次查看协程时,我希望并行处理大量数据,并等待其完成。我环顾四周,看到了RunBlocking和Await等,但不确定如何使用它。
到目前为止我已经
val jobs = mutableListOf<Job>()
jobs += GlobalScope.launch { processPages(urls, collection) }
jobs += GlobalScope.launch { processPages(urls, collection2) }
jobs += GlobalScope.launch { processPages(urls, collection3) }
然后我想知道/等待这些操作完成
发布于 2019-02-25 02:21:43
您可以使用async
构建器函数并行处理大量数据:
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
fun <T> CoroutineScope.asyncIO(ioFun: () -> T) = async(Dispatchers.IO) { ioFun() } // CoroutineDispatcher - runs and schedules coroutines
GlobalScope.launch
is not recommended to use,除非您希望协程在整个应用程序生命周期中运行,而不是过早取消。
编辑:就像罗曼·伊丽莎白提到的那样,你可以试着不使用awaitAll()
函数,除非你想在处理完所有数据后立即更新UI或做其他事情。
https://stackoverflow.com/questions/54854187
复制相似问题