Will M.
Will M.

Reputation: 1854

Spring WebFlux switchIfEmpty to return different type

public Mono<ServerResponse> getMessage(ServerRequest request) {
    //this call returns Mono<ApiClientResponse>
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
            .switchIfEmpty(/* Here */)
}

Excuse the slightly incomplete code, I was restructuring it when I ran into this problem. The gist is that where it says /* Here */ in the switchIfEmpty() call, the compiler is forcing a type of Mono<ApiClientResponse>, but when hystrixWrappedGetMessages() returns Mono.empty() I want to handle that by returning a 204 Mono<ServerResponse> for example, otherwise I want to return a 200. How can I accomplish that?

Ideally I could check if it was Mono.empty() in a map call, but it doesn't seem to enter map if it's an empty Mono. Thought about using optionals but they don't seem to play nicely with Monos.

Upvotes: 2

Views: 9244

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14810

You should be able to flatMap your response if good, and if an Mono#empty is returned the flatMap will get ignored.

public Mono<ServerResponse> getMessage(ServerRequest request) {
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
        .flatMap(response -> {
            // Do your processing here
            return ServerResponse.ok().body( .... );
        }.switchIfEmpty(ServerResponse.noContent());
}

Upvotes: 7

Related Questions