I am new to reactive programming and I want to implement spring-webclient on our existing project.
For simplicity, I created a pseudo code based from my original code. Here I am sending SMS to each provider. If condition is met then it will not proceed to next provider.
public List<Sms> send(List<Sms> smsRequests) {
return Flux.fromIterable(smsRequests)
.flatMap(smsRequest -> {
return Flux.fromIterable(smsRequest.getProviders())
.concatMap(smsProvider -> this.invokeApiUsingWebClient(smsProvider, smsRequest))
.filter(providerResponse -> providerResponse.getErrorStatus() == null)
.map(ProviderResponse::toSms)
.next(); // emits cancel(). Resulting to connection being closed.
})
.toStream()
.collect(Collectors.toList());
}
My problem is that this flow calls cancel()
every time next()
is invoke. Resulting to poor performance by not reusing the connection on the webclient threads.
See below logs.
TRACE 15112 [reactor-http-nio-1] [ExchangeFunctions] - [5e2f49c] Response 200 OK...
INFO 15112 [reactor-http-nio-1] [1] - onNext(...)
INFO 15112 [reactor-http-nio-1] [1] - cancel()
DEBUG 15112 [reactor-http-nio-1] [ExchangeFunctions] - [5e2f49c] Cancel signal (to close connection)
INFO 15112 [reactor-http-nio-1] [1] - onComplete()
TRACE 15112 [reactor-http-nio-2] [ExchangeFunctions] - [5e2f49c] Response 200 OK...
INFO 15112 [reactor-http-nio-2] [2] - onNext(...)
INFO 15112 [reactor-http-nio-2] [2] - cancel()
DEBUG 15112 [reactor-http-nio-2] [ExchangeFunctions] - [5e2f49c] Cancel signal (to close connection)
INFO 15112 [reactor-http-nio-2] [2] - onComplete()
Is there a possible way to refactor above code without emitting the cancel()
method?