Igor Kustov
Igor Kustov

Reputation: 797

Vert.x way to write coroutine blocking code

I do have the project that uses both coroutines and Vert.x.

I'm trying to write a wrapper function to run blocking code on vertx worker thread pool

Something like:

suspend inline fun <T> executeOnWorkerThread(crossinline block: () -> T) =
    withContext(**Vertx-Worker-ThreadPool**) {
        block()
    }

So it may be used like

 suspend fun usage(obj: Any): String = executeOnWorkerThread {
            try {
                // blocking code
            } catch (e: Exception) {
                // Exception handling
            }
        }

But this is not vert.x way. And I couldn't find the way to extract thread pool out of vert.x

Upvotes: 2

Views: 418

Answers (1)

Igor Kustov
Igor Kustov

Reputation: 797

suspend fun <T> awaitBlockingUnordered(block: () -> T): T {
    return awaitResult { handler ->
        val ctx = Vertx.currentContext()
        ctx.executeBlocking<T>(
            { fut -> fut.complete(block()) },
            false,
            { ar -> handler.handle(ar) }
        )
    }
}

Upvotes: 3

Related Questions