re: Vert.x Kotlin Coroutines VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

Hi Marco!

I don't think you misunderstood and this is an excellent question.

Coroutines themselves are another layer on top of the event callbacks. So you are wrapping the callback based API inside coroutines in order to enable composition of asynchronous functions through Coroutines rather than callback chains.

This does not necessarily mean that the coroutines are executed outside of the event loop. While you can use a different coroutine context (e.g. runBlocking when starting your Vert.x web server to make sure to resume only as soon as it is started), most of the cases your coroutines will run through the Vert.x dispatcher.

Let's say we are building a web application and we want to write our handlers as coroutines. We can do that with a simple helper function:

fun coroutineHandler(route: Route, handler: suspend (RoutingContext) -> Unit) {
    route.handler { ctx ->
        launch(ctx.vertx().dispatcher()) {
            try {
                handler(ctx)
            } catch (e: Exception) {
                log.error("Coroutine handler failed: $e")
                ctx.fail(e)
            }
        }
    }
}

With this helper we can add handlers to routes that do not take a callback but are suspending functions instead. The coroutine itself however will be launched through the Vert.x dispatcher of the routing context, so no new execution layer is added on top.

Inside your coroutine handlers you can then, e.g., use the Vert.x web client which has different sendAwait methods thanks to Vert.x Kotlin Coroutines so they will not block your event thread.

I hope it became clearer now. Please let me know if my explanation made sense and if you have more questions :)

 
code of conduct - report abuse