gpt4 book ai didi

java - 为什么我的协程异步只能在 runBlocking 内工作?

转载 作者:行者123 更新时间:2023-12-01 23:27:56 24 4
gpt4 key购买 nike

我正在尝试理解协程,但似乎比预期的更难理解,也许有人可以给我正确的方法。

我想要一个端点(简单的 hello world)来调用挂起的函数。

为此,我做了这个:

@GET
@Path("/test")
suspend fun test() : String {
coroutineScope {
async {
doSomething()
}.await()
}
return "Hello"
}

在 doSomething() 中我简单地这样做

private fun doSomething(){
logger.info("request")
}

看起来非常简单明了,阅读有关异步的内容 https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html它需要一个协程作用域 https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html ,所以我的代码应该可以工作。

但是当我调用我的方法时,我得到了这个:

! kotlin.KotlinNullPointerException: null
! at kotlin.coroutines.jvm.internal.ContinuationImpl.getContext(ContinuationImpl.kt:105)
! at kotlinx.coroutines.CoroutineScopeKt.coroutineScope(CoroutineScope.kt:179)

NPE 对此

 public override val context: CoroutineContext
get() = _context!!

当为 runBlocking 移动 coroutineScope 时,它可以工作。知道我缺少什么吗?我怎样才能做到这一点? (我试图避免使用 GlobalScope.async)

我使用 dropwizard 作为框架

最佳答案

不要让你的 Controller 具有挂起功能。它们只能从其他挂起函数或协程中调用。

我不知道如何准确地构建您的端点,但由于它已执行 - 内部没有协程上下文 - 因为我们没有定义任何内容!这就是为什么你会得到上下文的 NPE。

顺便说一句:下面的代码不会有异步行为,因为您立即等待 - 就像正常的顺序代码一样:

async {
doSomething()
}.await()
<小时/>

为了快速解决您的问题,我将如何重写它:

@GET
@Path("/test")
fun test() : String {
GlobalScope.launch { // Starts "fire-and-forget" coroutine
doSomething() // It will execute this in separate coroutine
}
return "Hello" // will be returned almost immediately
}

要了解有关上下文的更多信息,请阅读 thisTLDR:使用 Kotlin 的构建器和函数创建上下文 - 如 runBlocking

<小时/>

编辑

为了避免 GlobalScope. 函数,我们可以使用 runBlocking

@GET
@Path("/test")
fun test() : String = runBlocking {
val deferredResult1 = async { doSomething() } // Starts immediately in separate coroutine
val deferredResult2 = async { doSomethingElse() } // Starts immediately in separate coroutine

logger.print("We got:${deferredResult1 .await()} and ${deferredResult2 .await()}")

"Hello" // return value - when both async coroutines finished
}

关于java - 为什么我的协程异步只能在 runBlocking 内工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com