Only make second Spring WebClient request if the first comes back empty

Viewed 22

I have two data sources, and I want to call the second if a request to the first comes back empty or encounters an error. Both data sources are called via WebClient:

class MainClient {
    public Mono<FooDto> getFooByFooGuid(String fooGuid) {
        return webClient
                .get()
                .uri("/foos/{fooGuid}")
                .retrieve()
                .onStatus(HttpStatus::isError, () -> throw new RuntimeException())
                .bodyToMono(FooDto.class);
}

class FallbackClient {
    public Mono<Foo> getFooByFooGuid(String fooGuid) {
        // SAME
    }
}

Each source returns a slightly different version of the object. So, I'd like to conditionally chain these requests like so

public Entity findFooByFooGuid(String fooGguid) {
        return mainClient.getFooByFooGuid(headers, guid)
                .map(FooMapper::fromDto)
                .switchIfEmpty(fallbackClient.getFooByFooGuid(fooGuid))
                .subscribe();
}

...except this isn't working. How can I conditionally chain these requests in the idiomatic reactive way?

0 Answers
Related