协程范围构造函数内协程上下文的 Kotlin 组合
Kotlin composition of coroutine context inside constructor of coroutine scope
这段代码到底在做什么?
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 thread.
SupervisorJob
意味着与常规 Job
行为不同,当 children 之一失败时 parent 也会失败,而所有其他 children ] 同样,工作将照常进行。
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
,它允许使用 +
组合两个 objects 类型 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>
这段代码到底在做什么?
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 thread.
SupervisorJob
意味着与常规 Job
行为不同,当 children 之一失败时 parent 也会失败,而所有其他 children ] 同样,工作将照常进行。
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
,它允许使用 +
组合两个 objects 类型 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>