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

Time:06-06

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>>?

CodePudding user response:

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());
}
  • Related