vertx-lang-kotlin
vertx-lang-kotlin copied to clipboard
Provide a `future { }` coroutine builder
Describe the feature
In addition to the existing helper methods and builders, it would be useful to provide a coroutine builder that returns a Future<T>
.
Example:
// MyService is a service proxy.
class JokeServiceImpl: JokeService {
override fun fetchJokes(): Future<JsonArray> = future {
// Suspending methods can be used here to fetch the data.
jsonArray()
}
}
// Sub-par implementation; shouldn't actually be used.
fun <T> future(block: suspend () -> T) : Future<T> {
val dispatcher = Vertx.currentContext().dispatcher()
val promise = Promise.promse<T>()
try {
// Some magic to run this in a CoroutineScope / Vertx dispatcher.
launch {
promise.complete(block())
}
} catch (ex: Exception) {
promise.fail(ex)
}
return promise.future
}
Use cases
Presently, writing code that bridges coroutines and future (e.g. service proxies) can be awkward. You need to create a Promise
, launch a coroutine, and handle completion of the promise:
class JokeServiceImpl(private val vertx: Vertx) : JokeService {
override fun fetchJokes(): Future<JsonArray> {
val promise = Promise.promise<JsonArray>()
launch {
try {
val jokes: JsonArray = TODO() // suspending code to fetch jokes
promise.complete(jokes)
} catch (ex: Exception) {
promise.fail(ex)
}
}
return promise.future
}
}
The kotlin.coroutines project includes several helper functions similar to this.
For example:
-
Bridge a JDK 8 Future to a coroutine
fun returnsFuture(): CompletableFuture<String> = future { delay(1_000) // run a coroutine "Hello" }
-
Bridge a reactor
mono
to a coroutinefun returnsMono(): Mono<String> = mono { delay(1_000) // run a coroutine "Hello" }