【发布时间】:2019-11-13 11:09:50
【问题描述】:
withContext
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T (source)
Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.
suspend fun <R> coroutineScope(
block: suspend CoroutineScope.() -> R
): R (source)
Creates a CoroutineScope and calls the specified suspend block with this scope. The provided scope inherits its coroutineContext from the outer scope, but overrides the context’s Job.
withContext 采用 CoroutineContext,在其所有子代都完成后,两者似乎都是 complete。
在什么情况下withContext 或coroutineScope 应该比另一个更受欢迎?
例如:
suspend fun processAllPages() = withContext(Dispatchers.IO) {
// withContext waits for all children coroutines
launch { processPages(urls, collection) }
launch { processPages(urls, collection2) }
launch { processPages(urls, collection3) }
}
也可以
suspend fun processAllPages() = coroutineScope {
// coroutineScope waits for all children coroutines
launch { processPages(urls, collection) }
launch { processPages(urls, collection2) }
launch { processPages(urls, collection3) }
}
processAllPages() 都在做同样的事情吗?
更新:见Why does withContext await for the completion of child coroutines讨论
【问题讨论】:
标签: kotlin-coroutines coroutinescope withcontext