Flux.any correct use

2019-08-23 12:28发布

问题:

I have a Flux.fromIterable(list of ids) . I want to find out if any of the record is null .So I am trying to use Flux.any but I see that I does not even print anything inside any and directly goes to doOnEach as a result output is false. How can we fix this? The solution should not be limited to null check.It can be any boolean condition.


    Mono<Boolean> isAnyNull =Flux.fromIterable(request.getIds())
        .switchIfEmpty(Mono.error(new SomeException("No elements")))
        .flatMap(id->{
          return FooRepo.find(id);
          }).any(p->{
          System.out.println("check is any null p?."+p);
          return ((p==null)||(p.getId()==null));
        }).doOnEach(System.out::println);

I tried below as a temp weird fix but i am not sure if this is correct.Also I think it will only work for null.

Mono<Boolean> isAnyNull = Flux.fromIterable(request.getds())
        .switchIfEmpty(Mono.error(new SomeException("No elements")))
        .flatMap(id -> {
          return FooRepo.find(id);
         })
        .switchIfEmpty(Mono.error(new SomeException("INVALID_ID"))).hasElements()
        .doOnEach(System.out::println);

Update : This also works and check null using stream -Comments appreciated to improve

Flux.fromIterable(request.getIds())
     .switchIfEmpty(Mono.error(new SomeException("No elements")))
        .flatMap(id -> {
          return FooRepo.find(id);
        })
        .any(foo -> {
         return (Objects.nonNull(foo)||foo.getId()!=null);
        }).doOnEach(System.out::println);