0

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?

  • Why are you using next() method? if you read java doc https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#next-- next() emits the first element and call cancel - it's expected behavior – Yauhen Balykin Sep 03 '20 at 21:12
  • Yeah. Do you have anything on mind for alternative of `next()`? `single()` will still process all the elements in flux – Jerome Ryan Villamor Sep 04 '20 at 03:23
  • I don't think that you need to call next() method, because webclient return Mono(Response) - this is a 1 element, remove next() operator and check expectable result or not – Yauhen Balykin Sep 04 '20 at 06:26
  • what do you mean check expectable result? – user2627156 Aug 01 '23 at 20:09

0 Answers0