【发布时间】:2020-04-08 09:33:01
【问题描述】:
在示例中: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中,调用launch必须依赖一个CoroutineScope; 所以不能在扩展函数Route.coroutineHandler()中调用launch;
如果总是使用 GlobalScope.launch() 启动协程,如何正确管理生命周期?
所以我使用了流动的方法:
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中extend函数如何使用;
【问题讨论】:
标签: kotlin vert.x kotlin-coroutines