【问题标题】:collectList() returns an empty list and does not enter the defaultIfEmptycollectList() 返回一个空列表,不输入 defaultIfEmpty
【发布时间】:2021-04-13 15:22:06
【问题描述】:

我有以下代码:

@GetMapping("/enrollment/{id}")
public Mono<ResponseEntity<Response>> findByEnrollment(@PathVariable("id") String enrollment){
    return Mono.just(enrollment)
               .flatMap(e -> technomechanicalService.findByEnrollmentVehicle(e)
                                                    .collectList()
                                                    .map(t -> ResponseEntity.ok()
                                                                            .body(new Response(t, HttpStatus.OK.value(), null)))
                                                    .defaultIfEmpty(new ResponseEntity<>(new Response(null, HttpStatus.BAD_REQUEST.value(), "No se encontro la placa!"), 
                                                                            HttpStatus.BAD_REQUEST)));

}

当使用 mongodb 中不存在的值从客户端(邮递员)消费时,它不会转到 defaultIfEmpty。

我给你的解决方案是在地图前加一个过滤器。如下图:

@GetMapping("/enrollment/{id}")
public Mono<ResponseEntity<Response>> findByEnrollment(@PathVariable("id") String enrollment){
    return Mono.just(enrollment)
               .flatMap(e -> technomechanicalService.findByEnrollmentVehicle(e)
                                                    .collectList()
                                                    .filter(t -> {
                                                        if(!t.isEmpty()) return true;
                                                        return false;
                                                    })
                                                    .map(t -> ResponseEntity.ok()
                                                                            .body(new Response(t, HttpStatus.OK.value(), null)))
                                                    .defaultIfEmpty(new ResponseEntity<>(new Response(null, HttpStatus.BAD_REQUEST.value(), null), 
                                                                            HttpStatus.BAD_REQUEST)));

}

我的问题是 .defaultIfEmpty () 会去哪里?

【问题讨论】:

  • it does not go to the defaultIfEmpty 请更新它的去向?

标签: java spring-boot spring-webflux project-reactor


【解决方案1】:

defaultIfEmpty().collectList() 之后不起作用,因为.collectList() 返回带有空列表的 Mono,它不等于空,所以 defaultIfEmpty() 不起作用。

您可以更改您的方法顺序,但您的地图方法将在defaultIfEmpty() 方法之后起作用

【讨论】:

  • 好的,我知道defaultIfEmpty().collectList() 之后无法工作,因为它返回一个带有空列表的单声道。但那我该去哪里呢?
  • 您可以在 flatMap 中检查列表是否为空并从那里返回 mono#empty,或者执行其他操作。
  • 在本例中,您可以直接测试 map 中的列表 (t.isEmpty()),这使得 lambda 更加复杂,但完全避免了 flatMap 的开销
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多