简体   繁体   English

类中的GlobalScope.launch(coroutineContext)vs launch()扩展了CoroutineScope

[英]GlobalScope.launch(coroutineContext) vs launch() in a class extends CoroutineScope

As codes shown below, 如下所示的代码,

  1. Will two launchWithXXX functions run in MainScope ? launchWithXXXMainScope将运行两个launchWithXXX函数? Are they creating the same coroutine environment for running both jobs? 他们是否为运行这两个作业创建了相同的协程环境?
  2. Will both functions be canceled when 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.

相关问题 使用 GlobalScope.launch 和 CoroutineScope().launch 启动协程有区别吗? - Is there a difference between using GlobalScope.launch and CoroutineScope().launch to launch a coroutine? Kotlin 协程 GlobalScope.launch 与 runBlocking - Kotlin coroutines GlobalScope.launch vs runBlocking 为什么不使用 GlobalScope.launch? - Why not use GlobalScope.launch? kotlinx.coroutines 基本示例无法识别 GlobalScope.launch 提供的 CoroutineScope - kotlinx.coroutines basic example can't recognise CoroutineScope provided by GlobalScope.launch 在jetpack compose中替换GlobalScope.launch - replace GlobalScope.launch in jetpack compose 使用协程时使用 GlobalScope.launch 的效果 - Effect of using GlobalScope.launch while using coroutine GlobalScope.launch 是创建一个新线程还是在同一线程中运行? - Does GlobalScope.launch create a new thread or run in the same thread? GlobalScope.launch(Main) 中的同步函数:Kotlin - Synchronise function inside GlobalScope.launch(Main): Kotlin 如何对具有协程`GlobalScope.launch`的function进行单元测试 - How to unit test function that has coroutine `GlobalScope.launch` 如何从“GlobalScope.launch”块获取字符串作为返回值 - How to get String as a return value from "GlobalScope.launch" block
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM