Just a small example of how Kotlin coroutines are great

Today I had to implement a simple DB transactional call.

A transaction is a way to make few SQL queries executed together, and make sure they are either all executed or rollback in case one they failed. The SQL syntax for that is BEGIN and COMMIT/ ROLLBACK.

The function to implement accepts a lambda f() with multiple SQL queries and execute the lambda inside a transaction scope. After the transaction was committed a value from the queries is returned. This value is of the generic type A in our case.

Why not just use JDBC and blocking code?

We are implementing an async driver to access MySQL and PostgreSQL called jasync-sql. With the driver, all calls are async and non-blocking. For example, sendQuery() method has two flavors, both of them async. One return CompleteableFuture of the result and the other one is suspending. You pick the flavor based on your personal preference.


With coroutines that is pretty straight-forward: BEGIN transaction, execute the SQL query and then COMMIT. In case of failure, we need to call ROLLBACK.

Here is the code:

Clean isn’t it?

How was the same code implemented with callbacks?

What do you think?! Can you believe the code has similar functionality?

More complete versions can be see here:

And here:

Let me know what you think.

Coroutines is an old/new paradigm that is now available in many languages: go, javascript, C# and Kotlin. If you wan’t to learn more about it there are many resource including this excellent video:


“person in yellow coat standing on top of hill” by Justin Luebke on Unsplash

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store