如何在最新的 kotlin-coroutine 中使用 extend 函数中的协程

How use the coroutine within extend function in the latest kotlin-couroutine

示例中: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() ;

如果总是使用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)
        }
    }
}

不知道最近的协程里extend函数怎么用api;

您可以通过添加以下扩展来实现:

fun Route.suspendHandler(requestHandler: suspend (RoutingContext) -> Unit) {
  handler { ctx ->
    CoroutineScope(ctx.vertx().dispatcher()).launch {
      requestHandler(ctx)
    }.invokeOnCompletion {
      it?.run { ctx.fail(it) }
    }
  }
}

您可以将此扩展放在代码中的任何位置。