【发布时间】:2020-06-02 07:25:59
【问题描述】:
我正在努力了解suspendCoroutine 和suspendCancellableCoroutine。我认为它们在以下情况下可能有用:
- 协程启动时,检查用户是否登录。
- 如果没有,请询问凭据并暂停当前正在执行的协程。
- 提交凭据后,从暂停的同一行恢复协程。
这编译但永远不会超过“延迟”,即延续永远不会恢复:
import kotlinx.coroutines.*
fun main(args: Array<String>) {
println("Hello, world!")
runBlocking {
launch {
postComment()
}
}
}
var isLoggedIn = false
var loginContinuation: CancellableContinuation<Unit>? = null
suspend fun postComment() {
if (!isLoggedIn) {
showLoginForm()
suspendCancellableCoroutine<Unit> {
loginContinuation = it
}
}
// call the api or whatever
delay(1000)
println("comment posted!")
}
suspend fun showLoginForm() {
println("show login form")
// simulate delay while user enters credentials
delay(1000)
println("delay over")
isLoggedIn = true
// resume coroutine on submit
loginContinuation?.resume(Unit) { println("login cancelled") }
}
我已经尝试了所有我能想到的方法,包括将调用移至登录检查之外的suspendCancellableCoroutine,将showLoginForm 的内容包装在withContext(Dispatchers.IO) 中,使用coroutineScope.launch(newSingleThreadContext("MyOwnThread") 等等。我得到的印象从阅读互联网来看,这是一个有效的用例。我做错了什么?
【问题讨论】:
标签: asynchronous kotlin kotlin-coroutines continuations