Merging more than 8 Monos with Reactor

My current project uses the reactive programming paradigm. I don’t have much experience with it, but over the past months I found my way around it. One service that I’m currently working on needs to retrieve different data from other services to generate an excel export. Every call that the service makes returns a Mono and the results are combined into a data object that can then be used. This is done by merging the Mono results and then mapping them:

Mono.zip(
userGateway.getUsers(),
ordersGateway.getOrders()
)
.map { (users, orders) ->
UsersAndOrder(users, orders)
}

In my case, the existing code merged more service calls and my task involved adding more data to that data object. To be more specific, I had to change two locations in the code and adding the same service call.
The first location worked without a problem, but the second location gave me a weired signature error: Adding another Mono seemed to use another .zip(…) method.

It took me a while to realize that the .zip() method is implemented multiple times: there’s one implementation for two parameters, another one for three parameters, and so on. But there are only implementation up to 8 parameters. In the second location I added a ninth parameter. So what to do?

After some digging I discovered a static function that takes a vararg Mono parameter and a combinator function – it’s part of the reactor-kotlin-extensions library. The above example then looks like this:

zip(
userGateway.getUsers(),
ordersGateway.getOrders()
) {
UsersAndOrders(
it[0] as Users,
it[1] as Orders
)
}

It works a tiny bit different in the sense that you have to cast the parameters, as the types can’t be preserved, but I think it’s a good solution for the problem.

Links

Leave a Reply

Your email address will not be published. Required fields are marked *