Last active
February 18, 2017 13:56
-
-
Save mplatvoet/bd029656bd17412f02cd to your computer and use it in GitHub Desktop.
CompletableFuture with Kovenant Promises example
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
import nl.komponents.kovenant.* | |
import nl.komponents.kovenant.jvm.asDispatcher | |
import java.util.concurrent.CompletableFuture | |
import java.util.concurrent.ForkJoinPool | |
fun main(args: Array<String>) { | |
Kovenant.context { | |
// configure Kovenant with the same pool | |
// CompletableFutures use. By default it's | |
// the common pool. | |
workerContext.dispatcher = ForkJoinPool.commonPool().asDispatcher() | |
} | |
// Some CompletableFuture | |
val completableFuture = CompletableFuture.supplyAsync { | |
fib(13) | |
} | |
// Convert it to a Promise | |
val promise = completableFuture.toPromise() | |
// Use it as a Promise | |
promise success { | |
println("Hurray! fib(13) = $it") | |
} | |
// Can also just use kovenant promises directly with the | |
// same thread pool | |
task { fib(13) } success { | |
println("Hurray again! fib(13) = $it") | |
} | |
} | |
// Simple function to convert a CompletablePromise | |
// To Kovenant Promise | |
fun <T> CompletableFuture<T>.toPromise(): Promise<T, Exception> { | |
val deferred = deferred<T, Exception>() | |
// Use the synchronous callback | |
// Kovenant fire the callbacks asynchronous | |
// anyway, so avoid useless scheduling. | |
thenAccept { | |
deferred.resolve(it) | |
} | |
exceptionally { | |
deferred.reject(it.toException()) | |
null as T | |
} | |
return deferred.promise | |
} | |
private fun Throwable.toException(): Exception = when (this) { | |
is Exception -> this | |
else -> Exception(this) | |
} | |
private fun fib(n: Int): Int { | |
if (n < 0) throw IllegalArgumentException("negative numbers not allowed") | |
return when (n) { | |
0, 1 -> 1 | |
else -> fib(n - 1) + fib(n - 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment