kotlin - Kotlin:在创建协程范围时,是否应将工作与调度程序一起传递

标签 kotlin kotlin-coroutines

我在做

 private val uiScope = CoroutineScope(Dispatchers.Main)

创建一个协程镜,并使用它在我的片段中启动协程。
uiScope.launch {
        withContext(Dispatchers.Default) {
            ....
        }
        ....
    }

当片段从窗口分离时,我对uiScope进行了取消。在创建uiScope时,我还应该传递一个job()吗?

最佳答案

fun CoroutineScope 的文档对此很明确:

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.



对于顶级范围而言,使用传播其子项故障的作业不是最佳选择。您应该改为使用 MainScope 工厂功能。它不带任何参数,并精确地构造您需要的范围。从文档:

The resulting scope has SupervisorJob and Dispatchers.Main context elements.

关于kotlin - Kotlin:在创建协程范围时,是否应将工作与调度程序一起传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57165228/

相关文章:

android - 从消费者发送消息到回调流

android - 如何使用 kotlin 序列化我的类对象?

kotlin - 协程中的 IO 会导致暂停吗?

kotlin - 取消信号上的Kotlin流收集

operator-overloading - 为 "Number Classes"重载 + 和 += 运算符

kotlin - 如何并行运行多个 Kotlin 协程并等待它们完成后再继续

android - 每次 Activity 暂停和恢复时,StateFlow 都会发出

java - 如何在 Spring Boot 中通过 websocket 代理按照提交顺序发送消息?

android - Kotlin:如果网络断开连接,使用 ConnectivityManager 检查网络状态将返回 null。怎么来的?

kotlin - 如何在 Quarkus 中注册 Jackson 模块?