什么是挂起协程?

yby*_*byb 29 suspend callback coroutine kotlin kotlin-coroutines

我是一个初学者学习coroutines

不完全是,但我对 a 是什么有一点了解coroutine

suspend function也很难,但需要一点理解。

我正在一步步学习,但有些地方我不明白。

那是suspendCoroutine。在示例代码中,suspendCoroutineContinuation在块中使用,但我不知道这两个是什么。

我看过其他网站,但找不到任何可以轻松解释的地方。

您能简单地解释一下suspendCoroutine和 的Continuation用途吗?如果可能的话,可以举个例子吗?

Ser*_*gey 65

suspendCoroutine是一个构建器函数,主要用于将回调转换为suspend函数。举例来说,假设您有一些使用回调的遗留(或没有)Api。您可以轻松地将其转换为suspend函数以在协程中调用它。例如:

suspend fun getUser(id: String): User  = suspendCoroutine { continuation ->
      Api.getUser(id) { user ->
          continuation.resume(user)
      }
}
Run Code Online (Sandbox Code Playgroud)

这里我们有一个 Api 函数getUser,它在类中定义Api如下:

fun getUser(id: String, callback: (User) -> Unit) {...}
Run Code Online (Sandbox Code Playgroud)

suspendCoroutine暂停执行它的协程,直到我们决定通过调用适当的方法继续 - Continuation.resume...suspendCoroutine主要在我们有一些带有回调的遗留代码时使用。

使用函数suspendCoroutine将回调转换为suspend函数可以使代码在使用suspend函数时保持顺序。

例如,不要有这样的回调地狱:

Api.getUser(id) { user ->
      Api.getProfile(user) { profile ->
          Api.downloadImage(profile.imageId) { image ->
              // ...
          }
      } 
}
Run Code Online (Sandbox Code Playgroud)

应用suspendCoroutine这些回调并将其转换为suspend函数后,代码将如下所示:

val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...
Run Code Online (Sandbox Code Playgroud)

  • 我不明白你的问题。YouTube 上有很多关于“suspendCoroutine”的文档和教程,例如这个 https://www.youtube.com/watch?v=OmHePYcHbyQ (4认同)

cev*_*ing 5

suspendCoroutine是 Kotlin 中Scheme函数的名称call-with-current-continuation(缩写call/cc)。

\n

这段视频“Fresh Async With Kotlin \xe2\x80\xa2 Roman Elizarov \xe2\x80\xa2 GOTO 2018”对此进行了解释。

\n

《Kotlin 中的阴阳谜题》一文基于阴阳谜题进行了解释,阴阳谜题是call/cc. 其他用例在文章“Continuations by example:异常、时间旅行搜索、生成器、线程和协程”中进行了解释。

\n