Skip to content

Commit

Permalink
await Future
Browse files Browse the repository at this point in the history
  • Loading branch information
danslapman committed Sep 24, 2024
1 parent 4d64116 commit a6aa712
Showing 1 changed file with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import scala.concurrent.Future
import scala.concurrent.Promise
import scala.util.Failure
import scala.util.Success
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

fun <T> CoroutineScope.scalaFuture(
context: CoroutineContext = EmptyCoroutineContext,
Expand Down Expand Up @@ -59,4 +61,16 @@ fun <T> Future<T>.asDeferred(executor: ExecutionContext): Deferred<T> {
}
}, executor)
return result
}

suspend fun <T> Future<T>.await(executor: ExecutionContext): T {
return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
this.onComplete({ res ->
when(res) {
is Success -> cont.resume(res.value())
is Failure -> cont.resumeWithException(res.exception())
else -> throw IllegalStateException("Unreachable")
}
}, executor)
}
}

0 comments on commit a6aa712

Please sign in to comment.