任何人都可以明确功能之间的关系 CoroutineScope()和coroutineScope()?
当我尝试检查源代码时,我发现它们都是CoroutineScope.kt. 此外,coroutineScope()是suspend函数而另一个是normal函数
以下是我可以找到的文档:
/**
* Creates a [CoroutineScope] that wraps the given coroutine [context].
*
* If the given [context] does not contain a [Job] element, then a default `Job()` is created.
* This way, cancellation or failure or any child coroutine in this scope cancels all the other children,
* just like inside [coroutineScope] block.
*/
@Suppress("FunctionName")
public fun CoroutineScope(context: CoroutineContext): CoroutineScope =
ContextScope(if (context[Job] != …Run Code Online (Sandbox Code Playgroud) 要更改函数中的线程,我使用 CoroutineScope 或 withContext。我不知道有什么区别,但是使用 CourineScope 我也可以使用处理程序。
例子:
private fun removeViews(){
CoroutineScope(Main).launch(handler){
gridRoot.removeAllViews()
}
}
private suspend fun removeViews(){
withContext(Main){
gridRoot.removeAllViews()
}
}
Run Code Online (Sandbox Code Playgroud)
我从一个在后台线程 (IO) 上工作的协程调用这个函数。哪个比另一个更合适?
用给定的协程上下文调用指定的暂停块,暂停直到完成,然后返回结果。
但是,实际行为是它也在所有子协程上等待,并且不一定返回块的结果,而是在子协程中传播任何异常。
suspend fun main() {
try {
val result = withContext(coroutineContext) {
launch {
delay(1000L)
throw Exception("launched coroutine broke")
}
println("done launching")
42
}
println ("result: $result")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
Run Code Online (Sandbox Code Playgroud)
我希望可以打印出上述内容result: 42,然后再打印子协程中未捕获的异常。而是等待一秒钟,然后打印Error: launched coroutine broke。
因此,实际行为与coroutineScope构建者的行为相匹配。虽然这可能是有用的行为,但我认为它与文档相矛盾。应该将文档更新为类似内容coroutineScope吗?
给定的块及其所有子协程完成后,此函数将立即返回。
此外,这是否意味着,我们可以使用coroutineScope和withContext(coroutineContext)互换,是少了几分样板唯一的区别?