Search code examples
springspring-webfluxreactive-programmingproject-reactor

How to convert Mono<ResponseEntity<Object>> to Mono<ResponseEntity<Void>>


Hi I have an API returning Mono<ResponseEntity<Void>>, the API will call another API which returns Mono<ResponseEntity<Object>>, how do I convert the result from this other API to Mono<ResponseEntity<Void>>? e.g.

public Mono<ResponseEntity<Void>> api() {
    return anotherApi()
        .map(response -> ResponseEntity.ok().build())
        .onErrorReturn(ResponseEntity.badRequest().build());
}

The above works if I only have the map, but not when I add the onErrorReturn, it complains Type mismatch: cannot convert from Mono<ResponseEntity<Object>> to Mono<ResponseEntity<Void>>, why has it become Mono<ResponseEntity<Object>>?


Solution

  • The code is correct and this is just Java generics that couldn't infer type correctly.

    You could provide type explicitly

    public Mono<ResponseEntity<Void>> api() {
        return anotherApi()
            .<ResponseEntity<Void>>map(response -> ResponseEntity.ok().build())
            .onErrorReturn(ResponseEntity.badRequest().build());
    }
    

    or move onErrorReturn one level up

    public Mono<ResponseEntity<Void>> api() {
        return anotherApi()
            .onErrorReturn(ResponseEntity.badRequest().build())
            .map(response -> ResponseEntity.ok().build());
    }