[英]GlobalScope.launch(coroutineContext) vs launch() in a class extends CoroutineScope
As codes shown below, 如下所示的代码,
launchWithXXX
functions run in MainScope
? launchWithXXX
中MainScope
将运行两个launchWithXXX
函数? Are they creating the same coroutine environment for running both jobs? dispose()
is called? dispose()
时,两个函数都将被取消吗? class A : CoroutineScope by MainScope() {
fun launchWithGlobalScope() {
GlobalScope.launch(coroutineContext) {
// Run jobs
}
}
fun launchWithClassScope() {
launch {
// Run jobs too
}
}
fun dispose() {
cancel()
}
}
Answer for 1: No. MainScope
defines a scope for doing something with UI components. 对于1的答案:否
MainScope
定义了使用UI组件执行操作的范围。 So it runs in the UI thread of your platform. 因此它在您平台的UI线程中运行。
GlobalScope
is a scope with an own thread pool and runs the coroutine with one of those threads. GlobalScope
是具有自己的线程池的范围,并使用这些线程之一运行协程。
Answer for 2: cancel
does only stop the MainScope
in your example and all coroutines created with this scope. 对于2的答案:
cancel
只会停止示例中的MainScope
以及使用该范围创建的所有协程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.