Async call DynamoDB from Vert.x using Kotlin coroutines

When writing Vert.x verticles, everything is about non-blocking asynchronous operations, of course. Therefore if we want to have Amazon DynamoDB as our database, we want to also call it asynchronously. In this example I assume you already created the DynamoDB table.

First we start with creating the asynchronous DynamoDB client:

Then we create our Vert.x verticle:

The book is being POSTed as JSON, so to write it to DynamoDB we call PutItemAsync:

To make it even better, we can rewrite this to using coroutines instead. Coroutines is a new feature in Kotlin that allows for cleaning up some of these callbacks.

To have a nice integration between Kotlin coroutines and Vert.x, there is an additional Vert.x module you must add to your Gradle dependencies:

Read more about it here:

Then you must extend CoroutineVerticle instead of AbstractVerticle:

Note that start has now become a suspending function. From this function you can call other suspending functions.

If we look at PutItemAsync, it requires a com.amazonaws.handlers.AsyncHandler as a callback. But actually we really want to use awaitResult provided by the Vert.x Kotlin Coroutines integration module, which requires a different callback: io.vertx.core.Handler. Therefore we define our own coroutine that bridges the two:

Now we can use that to rewrite our handler:

Note that you must wrap a handler body in the launch block, because you want to invoke a coroutine, but handlers themselves cannot be suspending.
This is described here:

Using coroutines with Vert.x allows you to simplify a lot of callbacks to just code with standard exception handling. Much more readable!

Tom Wetjens

Tom is an agile full stack developer with a lot of experience in back end and front end development with Java, Spring, Angular and React. And continuous delivery pipelines based on Maven, Gradle and Docker.

More Posts - Website

Follow Me: