【问题标题】:How use the coroutine within extend function in the latest kotlin-couroutine如何在最新的kotlin-coroutine中使用extend函数中的协程
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-29
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多