如何将 CompletableFuture 转换为 Vert.X Future

How to convert a CompletableFuture to a Vert.X Future

我正在尝试在协程中使用 vertx 反应式 sql 客户端执行数据库事务。 不知何故,我不知道如何将 CompletableFuture 转换为所需的 io.vertx.core.Future 类型。是否有任何辅助方法或扩展可以轻松做到这一点?

val client : PgPool
... 

suspend fun someServiceFunction () {
    coroutineScope {
        client.withTransaction { connection ->
            val completableFuture = async {
                repository.save(connection, requestDTO)  //This is a suspend function
            }.asCompletableFuture()

            //Return type has to be a io.vertx.core.Future
            //How can I transform the completableFuture to it ?
        }
    }
}

感谢您的帮助!

我从 asCompletableFuture() 的代码中改编了这个作为替代。免责声明:我不使用 Vert.x 也没有测试这个。

fun <T> Deferred<T>.asVertxFuture(): Future<T> {
    val promise = Promise.promise<T>()
    invokeOnCompletion {
        try {
            promise.complete(getCompleted())
        }  catch (t: Throwable) {
            promise.fail(t)
        }
    }
    return promise.future()
        .onComplete { result ->
            cancel(result.cause()?.let {
                it as? CancellationException ?: CancellationException("Future was completed exceptionally", it)
            })
        }
}

我想知道将协程与 Vert.x 混合使用是否会影响性能,因为您没有使用 Vert.x 线程池。也许您可以创建一个借用其线程池的 Dispatchers.Vertx

Vert.x Future有一个转换方法:

future = Future.fromCompletionStage(completionStage, vertxContext)