Apollo
Apollo

Reputation: 3

Make simultaneous WebClient calls and get only the first completed

I'm quite newbie in webflux and I want to do the following thing: I want to make parallel http requests to the same url with different parameter values and to stop when I get the first non null (and non exceptional) result. I'm following the example from here https://www.baeldung.com/spring-webclient-simultaneous-calls but I have no idea how to stop when I got the result. Can anybody help me? Currently I have something like this:

        RetrySpec retrySpec = Retry.max(3);

        return webClient.get().uri("/getMyObject/{id}", id)
                .retrieve()
                .bodyToMono(MyObject.class)
                .retryWhen(retrySpec);
    }

    public Flux<> getMyObjs(List<String> ids) {
        return Flux.fromIterable(ids)
                .parallel(Runtime.getRuntime().availableProcessors())
                .runOn()
                .flatMap(this::getMyObject)
                .;//// Stop when I get first non exceptional value
    }

Upvotes: 0

Views: 809

Answers (1)

Nipuna Saranga
Nipuna Saranga

Reputation: 1220

Try the next() operator in Flux.

public Mono<MyObject> getMyObjs(List<String> ids) {
        return Flux.fromIterable(ids)
                .parallel(Runtime.getRuntime().availableProcessors())
                .runOn()
                .flatMap(this::getMyObject)
                .next();// Emit only the first item emitted by this Flux, into a new Mono. If called on an empty Flux, emits an empty Mono.
}

Reference: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#next--

However check the firstWithSignal & firstWithValue operator as well. https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#firstWithSignal-java.lang.Iterable- https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#firstWithValue-java.lang.Iterable-

When I get a problem like this, normally I check the documentation to find a proper operator from Flux API.

Upvotes: 1

Related Questions