我正在阅读 Kotlin Coroutine 并且知道它是基于 suspend
函数的。但是suspend
是什么意思呢?
协程或函数被挂起?
来自 https://kotlinlang.org/docs/reference/coroutines.html
Basically, coroutines are computations that can be suspended without blocking a thread
我听到人们常说“挂起功能”。但我认为是协程因为等待函数完成而被挂起? “suspend”通常表示“停止操作”,此时协程处于空闲状态。
我们应该说协程被挂起吗?
哪个协程被挂起?
来自 https://kotlinlang.org/docs/reference/coroutines.html
To continue the analogy, await() can be a suspending function (hence also callable from within an async {} block) that suspends a coroutine until some computation is done and returns its result:
async { // Here I call it the outer async coroutine
...
// Here I call computation the inner coroutine
val result = computation.await()
...
}
它说“暂停协程直到完成某些计算”,但协程就像一个轻量级线程。那么如果协程被挂起,如何进行计算呢?
我们看到 await
在 computation
上被调用,所以它可能是 async
返回 Deferred
,这意味着它可以启动另一个协程
fun computation(): Deferred<Boolean> {
return async {
true
}
}
引用说暂停协程。它是指 suspend
外部 async
协程,还是 suspend
内部 computation
协程?
suspend
是否意味着外部 async
协程正在等待(await
)内部 computation
协程完成后,它(外部 async
协程)空闲(因此称为挂起)并将线程返回到线程池,当子 computation
协程完成时,它(外部async
coroutine) 唤醒,从池中获取另一个线程并继续?
我之所以提到线程是因为https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
The thread is returned to the pool while the coroutine is waiting, and when the waiting is done, the coroutine resumes on a free thread in the pool
最佳答案
挂起函数是所有协程的核心。 挂起函数只是一个可以在以后暂停和恢复的函数。他们可以执行长时间运行的操作并等待它完成而不会阻塞。
挂起函数的语法与普通函数的语法相似,只是增加了suspend
。关键词。它可以接受一个参数并有一个返回类型。但是,挂起函数只能由另一个挂起函数或在协程内调用。
suspend fun backgroundTask(param: Int): Int {
// long running operation
}
在后台,挂起函数被编译器转换为另一个没有挂起关键字的函数,它接受一个类型为 Continuation<T>
的附加参数。 .例如上面的函数,编译器会转换成这个:
fun backgroundTask(param: Int, callback: Continuation<Int>): Int {
// long running operation
}
Continuation<T>
是一个包含两个函数的接口(interface),当函数挂起时,如果发生错误,则调用这些函数以返回值或异常来恢复协程。
interface Continuation<in T> {
val context: CoroutineContext
fun resume(value: T)
fun resumeWithException(exception: Throwable)
}
https://stackoverflow.com/questions/47871868/
相关文章:
generics - 如何在 Kotlin 中获取泛型参数类
android - 房间持久性 : Error:Entities and Pojos must ha
enums - 如何在 Kotlin 中为枚举创建 "static"方法?
android - 如何将 Kotlin 与 Proguard 一起使用
android - 当列名相同时,如何表示与 Android Room 的 "many to man
java - 如何在 Kotlin 中组合 Intent 标志
android-studio - Kotlin:为什么 Android Studio 中的大多数变量