Using Recursion with Webflux/Reactor

Anoop Hallimala
1 min readSep 1, 2021

--

There is a often a need to call the same service/method again and again, where the output of the previous call will be the input of the current call.

We can use recursion to achieve this.

We have a service which simply increments the count and returns the updated value.

public static Mono<Integer> incrementIntegerService(Integer current) {
log.info("Inside incrementIntegerService. Current value: " + current);
return Mono.just(current).map(integer1 -> current + 1);
}

The requirement is to call this service ‘n’ number of times, where the input of each call is the output of the previous call.

We can achieve this using recursion.

public static Flux<Integer> recursiveService(Integer number) {

return Flux.just(number)
.flatMap(Application::incrementIntegerService)
.filter(integer -> integer <= 10) //Stop condition: Stop after 10 recursions
.doOnNext(integer -> log.info("Before call:" + integer))
.flatMap(integer -> recursiveService(integer)
.defaultIfEmpty(integer));
}

We start off the chain by providing an initial input. Then, recursive call to the same service is made with an updated input.

We need a stop condition, this is where we use filter operator. This stop condition can be updated based on the requirement. defaultIfEmpty puts the final value back in the chain, and the methods calls start unwrapping.

We kick things off by calling the recursiveService from the main method.

public static void main(String[] args) {
recursiveService(1)
.doOnNext(integer -> System.out.println("Final value: "+ integer))
.subscribe();
}

This will print the final value once the recurvise chain ends and the value is printed on the screen.

--

--

Anoop Hallimala

I work as a Staff Engineer at vmware. I dabble in Open Source and Cloud-Native tech. I believe Software has to be invisible or beautiful.