Kotlin中,在协程作用域的构造函数内组合协程上下文。

huangapple go评论78阅读模式
英文:

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 &lt;T&gt; CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -&gt; T
): Deferred&lt;T&gt;

huangapple
  • 本文由 发表于 2020年1月3日 22:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定