【发布时间】:2020-02-06 14:08:25
【问题描述】:
我正在尝试理解协程,但似乎比预期的更难理解,也许有人可以给我正确的方法。
我想要一个调用挂起函数的端点(简单的 hello world)。
为此我做了这个:
@GET
@Path("/test")
suspend fun test() : String {
coroutineScope {
async {
doSomething()
}.await()
}
return "Hello"
}
在 doSomething() 中我很简单地这样做了
private fun doSomething(){
logger.info("request")
}
看起来很简单直接,阅读 async 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!!
将coroutineScope 移动为runBlocking 时,它可以工作。知道我缺少什么吗?我怎样才能使这项工作? (我尽量避免使用GlobalScope.async)
我正在使用 dropwizard 作为框架
【问题讨论】:
标签: java kotlin kotlin-coroutines