vertx-lang-kotlin-coroutines 理解

vertx-lang-kotlin-coroutines understanding

这将是一个非常基本的问题,但我无法理解。我正在阅读有关 kotlin 协同程序与 Vertx 平台的集成 (here) 并遇到以下代码片段。

val vertx = Vertx.vertx()

GlobalScope.launch(vertx.dispatcher()) {
  val timerId = awaitEvent<Long> { handler ->
    vertx.setTimer(1000, handler)
  }
  println("Event fired from timer with id $timerId")
}

而且是页面上的定义

The vertx.dispatcher() returns a coroutine dispatcher that execute coroutines using the Vert.x event loop.

The awaitEvent function suspends the execution of the coroutine until the timer fires and resumes the coroutines with the value that was given to the handler.

More details are given in the next sections on handlers, events and stream of events.

现在我的问题是 handler 的用途是什么,它是什么类型?

Vert.x 中的许多异步操作将 Handler<T> 作为最后一个参数。 vertx.setTimer() 是此类异步函数之一,它在计时器触发时调用 handler 。根据 docs of Vertx.setTimer() method 它接受 handler: Handler<Long> 作为第二个参数。我们可以得出结论 Handler<T> 的泛型是 Long.

暂停功能awaitEvent takes lambda block as the parameter, which in turn receives parameter of type Handler<T>. According to the docs:

The block is executed with a Handler<T> argument that shall be called once. When the handler is called, awaitEvent returns the value that the handler received.

所以当将handler传递给vertx.setTimer(1000, handler)函数时,它会在延迟(1000毫秒)结束后调用handler,然后依次调用awaitEvent函数returns 处理程序接收到的值(计时器 ID)。