vertx-lang-kotlin icon indicating copy to clipboard operation
vertx-lang-kotlin copied to clipboard

Provide a `future { }` coroutine builder

Open rgmz opened this issue 2 years ago • 0 comments

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:

rgmz avatar Nov 02 '21 02:11 rgmz