简体   繁体   English

在Kotlin,Coroutine和Continuation之间的区别是什么?

[英]In Kotlin, what's the difference between the terms Coroutine and Continuation?

It seems like these two terms are used interchangeably. 似乎这两个术语可以互换使用。 Yet, there also seems to be some difference that I'm struggling to put my finger on. 然而,似乎还有一些不同之处,我正在努力指责。 Is there a difference? 有区别吗?

It's true, these two are quite closely related. 的确,这两者密切相关。 To resume a coroutine, you actually call continuation.resume() . 要恢复协程,您实际上调用continuation.resume()

Each coroutine has its associated continuation object. 每个协同程序都有其相关的延续对象。 Actually, you don't need anything else but that object, it contains the complete state of the coroutine. 实际上,除了该对象之外,您不需要任何其他内容,它包含协程的完整状态。

To a certain degree, Kotlin uses "coroutine" to also include the coroutine context, which gives the coroutine the knowledge how exactly to suspend itself, where to keep the continuation while suspended, and how to resume (dispatch) it later. 在某种程度上,Kotlin使用“coroutine”还包括协程上下文,它为协程提供了如何准确暂停自身,在暂停时保持连续的位置,以及如何在以后恢复(发送)它的知识。 But you can also use the Unconfined coroutine context, which is almost as good as no context at all, and be in total control of resumption with nothing but the continuation object being preserved: 但是你也可以使用Unconfined coroutine上下文,它几乎和没有上下文一样好,并且完全控制恢复,只保留连续对象:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

var continuation: Continuation<Unit>? = null

fun main(args: Array<String>) {
    GlobalScope.launch(Dispatchers.Unconfined) {
        println("Suspending")
        suspendCoroutine<Unit> { cont ->
            continuation = cont
        }
        println("Resumed!")
    }
    println("After launch")
    continuation!!.resume(Unit)
    println("After continuation.resume(Unit)")
}

Here you can see that we reproduced the whole suspend-resume scenario while keeping nothing but the Continuation object. 在这里你可以看到我们重现了整个暂停 - 恢复场景,同时保留了Continuation对象。

My conclusion is that, due to the features of Kotlin's coroutine design (especialy the fact that they are stackless ), there's a blurry line between the concepts of "coroutine" and "continuation". 我的结论是,由于Kotlin的协同设计的特点(特别是它们是无堆叠的 ),“coroutine”和“continuation”的概念之间存在着模糊的界限。

Coroutines are procedures that take turns doing their task and then suspend to give control to the other coroutines in the group, and resume task. 协同程序是轮流执行任务然后暂停以控制组中其他协同程序并恢复任务的过程。

Continuation is the stack that controls the flow of the program, that allows it to skip into different parts of your program. Continuation是控制程序流程的堆栈,允许它跳转到程序的不同部分。 You could use it to control the flow including coroutine like a global switch . 您可以使用它来控制流程,包括像全局switch一样的协程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM