Created
December 12, 2018 14:41
-
-
Save IRus/831d5da4234a7ff13cc6dbbccc56064e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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