Just a small example of how Kotlin coroutines are great

Nov 6, 2018 · 2 min read

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:

suspend fun <A> inTransaction(
f: suspend (Connection) -> A): A {
try {
val result = f(this)
return result
} catch (e: Throwable) {
throw e

How was the same code implemented with callbacks?

fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>)
: CompletableFuture<A> {
return this.sendQuery("BEGIN").flatMap { _ ->
val p = CompletableFuture<A>()
f(this).onComplete { ty1 ->
if (ty1.isFailure) "ROLLBACK" else "COMMIT")
.onComplete { ty2 ->
if (ty2.isFailure && ty1.isSuccess)
p.failed((ty2 as Failure).exception)

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:


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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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