If you have ever worked with the Vert.x EventBus in Kotlin, you might have wondered about ways to make it more type-safe. In this article, I'd like to introduce a tiny library that aims to solve this exact problem. It provides an idiomatic and type-safe way of communicating via the EventBus and in addition avoids unnecessary serialization and deserialization.
Getting Started
Imagine we need to create a division service. We want to give it two doubles and expect it to reply with the result or an error if the operation failed.
If we were to model the input and output for this service in Kotlin we might come up with something like this:
data class DivisionRequest(val dividend: Double, val divisor: Double)
sealed class Division {
data class Success(val quotient: Double) : Division()
data class Error(val message: String) : Division()
}
With the data for our service ready, we can start generating the EventBus extensions!
Describing the Service
For the code generation to work, we need to annotate our service Verticle:
@EventBusService(
topic = "co.selim.sample.division",
consumes = DivisionRequest::class,
produces = Division::class,
propertyName = "divisionRequests",
functionName = "divide"
)
class DivisionVerticle : CoroutineVerticle() {
Now the library has all it needs to generate type-safe code to interact with our service.
Communicating with the Service
The library will generate two extensions on the Vertx class:
- An extension function to call the service:
suspend fun Vertx.divide(request: DivisionRequest): Division
- An extension property with the requests that the service can handle:
val Vertx.divisionRequests: Flow<EventBusServiceRequest<DivisionRequest, Division>>
With these two extensions we can communicate with our service while not having to worry about sending in or receiving the wrong type.
Avoiding Serialization
The generated extensions avoid unnecessary serialization and deserialization by making use of a special EventBus codec. This provides better performance and enables us to send and receive Kotlin types.
Using it in Your Project
The code is hosted on GitHub and instructions for adding it to your dependencies can be found in the readme.
Top comments (1)
Thank you for this blog post. @EventBusService is a really nice idea. Loved it and now will think if I can use this or similar concept in my project.