这段代码到底在做什么?
private val supervisorJob = SupervisorJob()
protected val presenterScope = CoroutineScope(Dispatchers.Main + supervisorJob)
Dispatchers.Main + supervisorJob
的结果是什么?我了解它一定是某种组合,但是它如何工作?怎么称呼它?谢谢
最佳答案
有很多问题。
What exactly is this code doing?
您可以如下所示:此代码创建一个新的
CoroutineScope
,将调度程序设置为Main
,将行为设置为SupervisorJob
Dispatchers.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/