【问题标题】:How to get elements in one Flux that does not appear in another Flux如何在一个 Flux 中获取未出现在另一个 Flux 中的元素
【发布时间】:2020-01-04 04:41:07
【问题描述】:

我是 Spring Reactive Project 的新手。使用中出现问题。 我有两个 Flux,一个有更多元素,比如

Flux<Integer> bigFlux = Flux.range(1, 10);

还有人喜欢

Flux<Integer> smallFlux = Flux.just(3, 7);

如何获取 bigFlux 中未出现在 smallFlux 中的元素? 我不知道该使用哪个运算符。

我试过了:

Flux<Integer> flux = bigFlux.filterWhen(one -> smallFlux.hasElement(one).map(a->!a));

但这并不明智,我通过复杂的操作得到了smallFlux,比如查询数据库,flatMap操作。这样,bigFlux中有多少个元素,这些操作会重复多少次。

其实smallFlux就是这样得到的。

Flux<File> usedFile = repository.findAll()
                .flatMap(one -> {
                    List<File> used = someMethods(one);
                    return Flux.fromIterable(used);
                });

还有其他更好的解决方案吗,谢谢。

【问题讨论】:

    标签: spring-webflux reactive


    【解决方案1】:

    我认为这将是一个更清洁、更快捷的解决方案

    final Flux<Integer> bigListFlux = Flux.just(1, 2, 3);
    
    final Flux<Integer> smallListFlux = Flux.just(3, 5, 6);
    
    Mono.zip(bigListFlux.collectList(), smallListFlux.collectList(), (bigList, smallList) -> {
    
      bigList.removeAll(smallList);
    
      return bigList;
    }).flatMapMany(Flux::fromIterable).map(element -> {
    
      System.out.println("element = " + element);
    
      return element;
    }).subscribe(); // do not use subscribe/block in actual production code.
    

    我使用了Mono.zip的以下变体

    https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#zip-reactor.core.publisher.Mono-reactor.core.publisher.Mono-java.util.function.BiFunction-

    【讨论】:

      猜你喜欢
      • 2020-02-24
      • 2021-03-21
      • 2021-08-05
      • 2021-07-31
      • 2018-09-15
      • 2020-07-30
      • 2021-12-12
      • 2021-03-12
      • 1970-01-01
      相关资源
      最近更新 更多