在示例中:kotlin-examples/coroutines/src/main/kotlin/movierating/App.kt 有如下代码:
fun Route.coroutineHandler(fn: suspend (RoutingContext) -> Unit) {
handler { ctx ->
launch(ctx.vertx().dispatcher()) {
try {
fn(ctx)
} catch (e: Exception) {
ctx.fail(e)
}
}
}
}
在最新的kotlin-coroutine中,调用启动必须依赖于CoroutineScope; 因此无法在扩展函数Route.coroutineHandler()中调用启动。
如果始终使用GlobalScope.launch()启动Couroutine,如何正确管理生命周期?
所以我使用了流动方法:
interface SuspendHandler<E>: Handler<E>,CoroutineScope {
override fun handle(event: E) {
launch {
suspendHandle(event)
}
}
suspend fun suspendHandle(event: E)
}
fun <E> vertxSuspendHandler(vertx: Vertx = getDefaultVertx(),
block:suspend CoroutineScope.(E)->Unit): SuspendHandler<E>{
return object: SuspendHandler<E> {
override val coroutineContext: CoroutineContext
get() = vertx.dispatcher()
override suspend fun suspendHandle(event: E) {
block(event)
}
}
}
我不知道如何在最新的协程api中使用扩展功能;
答案 0 :(得分:0)
您可以通过添加以下扩展名来实现:
fun Route.suspendHandler(requestHandler: suspend (RoutingContext) -> Unit) {
handler { ctx ->
CoroutineScope(ctx.vertx().dispatcher()).launch {
requestHandler(ctx)
}.invokeOnCompletion {
it?.run { ctx.fail(it) }
}
}
}
您可以将此扩展名放在代码中的任何位置。