kotlin - 协程范围的构造函数中的协程上下文的Kotlin组成

标签 kotlin kotlin-coroutines

这段代码到底在做什么?

private val supervisorJob = SupervisorJob()
protected val presenterScope = CoroutineScope(Dispatchers.Main + supervisorJob)
Dispatchers.Main + supervisorJob的结果是什么?我了解它一定是某种组合,但是它如何工作?怎么称呼它?
谢谢

最佳答案

有很多问题。

What exactly is this code doing?



您可以如下所示:此代码创建一个新的CoroutineScope,将调度程序设置为Main,将行为设置为SupervisorJobDispatchers.Main表示协程将在主线程上执行。通常,这是指Android UI线程。
SupervisorJob意味着,与常规Job行为不同,当一个 child 的失败也会使 parent 失败,而所有其他 child 也会失败,这项工作将照常进行。

What is the result of Dispatchers.Main + supervisorJob?



结果是CoroutineContext。您可以将其视为具有不同键值的哈希映射。

I understand it must be some sort of composition but how does it work?



你是对的。如果查看CoroutineContext的实现,您会看到它实现了operator fun plus,它允许使用+组合两个CoroutineContext类型的对象

And how is it called?



通常协程方法是对CoroutineScope的扩展方法。例如,如果我们查看async():
public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T>

关于kotlin - 协程范围的构造函数中的协程上下文的Kotlin组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580763/

相关文章:

mysql - 为什么在添加列时所有行都获得空值?

android - 在 Alert Dialog Builder 中启动协程

android - 撰写崩溃并出现错误 "kotlinx.coroutines.channels.Channel"

android - Coroutine GlobalScope 延迟触发

android - 意外的行为改造+协程

kotlin - Kotlin 中函数变量的空安全运算符

Kotlin 扩展日志函数与 logback(slf4j)

android - 用于 kotlin 的 Android 中的静态等效项,以避免处理程序内存泄漏

kotlin - 处理 Kotlin 函数参数中的挂起和非挂起

android - Kotlin 中 globalScope 、 corountineScope 和 viewScope 的区别