From 4d5c9153ab5b4fdf6ff66c1e5c26fa0aba4f2aae Mon Sep 17 00:00:00 2001 From: Graham Date: Sun, 16 May 2021 13:17:18 +0100 Subject: [PATCH] Add support for converting a Netty Future to a CompletableFuture Signed-off-by: Graham --- .../org/openrs2/net/FutureExtensions.kt | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/net/src/main/kotlin/org/openrs2/net/FutureExtensions.kt b/net/src/main/kotlin/org/openrs2/net/FutureExtensions.kt index 6dd9464288..bdbe6d42a4 100644 --- a/net/src/main/kotlin/org/openrs2/net/FutureExtensions.kt +++ b/net/src/main/kotlin/org/openrs2/net/FutureExtensions.kt @@ -1,6 +1,7 @@ package org.openrs2.net import io.netty.util.concurrent.Future +import java.util.concurrent.CompletableFuture import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine @@ -24,3 +25,25 @@ public suspend fun Future.awaitSuspend(): V { } } } + +public fun Future.asCompletableFuture(): CompletableFuture { + if (isDone) { + return if (isSuccess) { + CompletableFuture.completedFuture(now) + } else { + CompletableFuture.failedFuture(cause()) + } + } + + val future = CompletableFuture() + + addListener { + if (isSuccess) { + future.complete(now) + } else { + future.completeExceptionally(cause()) + } + } + + return future +}