Skip to content

Commit

Permalink
Convertion to Deferred
Browse files Browse the repository at this point in the history
  • Loading branch information
danslapman committed Sep 24, 2024
1 parent a8ac95d commit 4d64116
Showing 1 changed file with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import kotlinx.coroutines.*

import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.util.Failure
import scala.util.Success

fun <T> CoroutineScope.scalaFuture(
context: CoroutineContext = EmptyCoroutineContext,
Expand Down Expand Up @@ -44,4 +47,16 @@ fun Job.asScalaFuture(): Future<scala.runtime.BoxedUnit> {
else promise.failure(cause)
}
return promise.future()
}

fun <T> Future<T>.asDeferred(executor: ExecutionContext): Deferred<T> {
val result = CompletableDeferred<T>()
this.onComplete({ res ->
when(res) {
is Success -> result.complete(res.value())
is Failure -> result.completeExceptionally(res.exception())
else -> throw IllegalStateException("Unreachable")
}
}, executor)
return result
}

0 comments on commit 4d64116

Please sign in to comment.