简体   繁体   中英

Merge two mono objects and return responseEntity object?

I have the following controller

@RestController
@RequestMapping("/view")
public class ManiController {
@GetMapping("/{channelId}/**")
public Mono<ResponseEntity<String>> manifest(@RequestParam(name = "sid", required = false) String sessionId) {
    return redisController.getData(sessionId).flatMap(sessionInfo -> {
        if(sessionInfo!=null){
            redisController.confirm(sessionInfo).map(data->{
                return new ResponseEntity<>(data, HttpStatus.OK);
            });
        }
    });
}
}

I do not get callback on redisController.confirm(sessionInfo).map and controller returns blank response.

Reactor does not accept null values.

Most likely, redisController.getData(sessionId) returns an empty Mono.

Empty publisher will not emit any values, only a completion signal. Therefore, none of your operations past the empty publisher would be called. To define a fallback, you can either provide an alternate operation using switchIfEmpty (there's also a defaultIfEmpty method to provide a pre-computed fallback).

Your snippet might be adapted to something like this:

redisController.getData(sessionId)
               .flatMap(redisController::confirm)
               .map(ResponseEntity::ok)
               .switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expired or unexisting session")));

In this example, if your redisController does not send back any data, a bad request Response will be sent back.

Try to return result from calling redisController.getData

public Mono<ResponseEntity<String>> manifest(@RequestParam(name = "sid", required = false) String sessionId) {
    return redisController.getData(sessionId).flatMap(sessionInfo -> sessionInfo!=null
                ? redisController.confirm(sessionInfo).map(data->new ResponseEntity<>(data, HttpStatus.OK))
                : Mono.just(ResponseEntity.notFound())
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM