英文:
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?
private val supervisorJob = SupervisorJob()
protected val presenterScope = CoroutineScope(Dispatchers.Main + supervisorJob)
What is the result of Dispatchers.Main + supervisorJob
? I understand it must be some sort of composition but how does it work? And how is it called?
Thank you
答案1
得分: 5
以下是翻译的部分:
这有很多问题。
这段代码到底在做什么?
您可以这样看待:这段代码创建了一个新的CoroutineScope
,将调度器设置为Main
,行为设置为SupervisorJob
。
Dispatchers.Main
表示协程将在主线程上执行。通常,这指的是Android的UI线程。
SupervisorJob
意味着与常规的Job
行为不同,当其中一个子任务失败时,也会使父任务以及所有其他子任务失败,而该任务将继续正常运行。
Dispatchers.Main + supervisorJob的结果是什么?
结果是CoroutineContext
。您可以将其视为不同键化值的哈希映射。
我明白它必须是某种组合,但它是如何工作的?
您是正确的。如果查看CoroutineContext
的实现,您会看到它实现了operator fun plus
,这允许使用+
来组合两个类型为CoroutineContext
的对象。
它是如何调用的?
通常,协程方法是在CoroutineScope
上的扩展方法。如果我们看看async()
,例如:
public fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>
英文:
That's a lot of questions.
> What exactly is this code doing?
You can look at this as follows: this code creates a new CoroutineScope
, with dispatcher set to Main
and and behaviour set to SupervisorJob
Dispatchers.Main
means that the coroutine will execute on the main thread. Usually this refers to Android UI thread.
SupervisorJob
means that unlike regular Job
behaviour, when failure of one of the children will also fail the parent, and all the other children too, the job will just continue as usual.
> What is the result of Dispatchers.Main + supervisorJob?
The result is CoroutineContext
. You can think of it as a hash map of different keyed values.
> I understand it must be some sort of composition but how does it work?
You are correct. If you look at CoroutineContext
implementation, you'll see that it implements operator fun plus
, which allows to use +
to combine two objects of type CoroutineContext
> And how is it called?
Usually coroutine methods are extension methods on CoroutineScope
. If we look at async()
, for example:
public fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论