Skip to content

Instantly share code, notes, and snippets.

@IRus
Created December 12, 2018 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IRus/831d5da4234a7ff13cc6dbbccc56064e to your computer and use it in GitHub Desktop.
Save IRus/831d5da4234a7ff13cc6dbbccc56064e to your computer and use it in GitHub Desktop.
fun <T : Any> Future<T>.toDeferred(
scope: CoroutineScope = GlobalScope,
waitTime: Long = 100
): Deferred<T> {
val future = this
val deferred = CompletableDeferred<T>()
var isDone = false
scope.launch {
while (isActive && !isDone) {
if (future.isDone) {
try {
isDone = true
deferred.complete(future.get())
} catch (e: Exception) {
isDone = true
deferred.completeExceptionally(e)
}
} else if (future.isCancelled) {
isDone = true
deferred.cancel()
} else {
delay(waitTime)
}
}
}
return deferred
}
suspend fun main(args: Array<String>) {
val f: Future<String> = CompletableFuture.supplyAsync {
Thread.sleep(2000)
"Hello!"
}
val f1: Future<String> = CompletableFuture.supplyAsync {
throw RuntimeException("Boom!")
}
listOf(f, f1).map { it.toDeferred() }.awaitAll().forEach { println(it) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment