【问题标题】:Split a Flux into two based on a condition without GroupBy根据没有 GroupBy 的条件将 Flux 一分为二
【发布时间】:2021-11-11 14:34:41
【问题描述】:

对于给定的数据流:

Flux<Integer> evenFlux = Flux.just(1, 2, 3, 4, 5, 6, 7)
                         .filter(i -> i % 2 == 0)

Flux<Integer> oddFlux = Flux.just(1, 2, 3, 4, 5, 6, 7)
                         .filter(i -> i % 2 != 0)

我怎样才能使用单个管道进行拆分? 所有过滤的元素到一个Flux,丢弃的元素到另一个Flux。使用onDiscardHook 什么的?

注意:我需要对新的Flux 进行repeat() 操作。无法在 GroupedFlux 上执行重复。

【问题讨论】:

标签: java project-reactor


【解决方案1】:

视情况而定,您有两种选择:

选项 1 是从热输入源创建两个新管道:

ConnectableFlux<Integer> input = Flux.range(1,7).publish();

//Pipeline 1
input.filter(i -> i % 2== 0)
    .subscribe(e -> System.out.println("Even stream value: " + e));

//Pipeline 2
input.filter(i -> i % 2 != 0)
    .subscribe(o -> System.out.println("Odd stream value: " + o));

input.connect();

选项 2 是在单个订阅者中处理结果,例如按以下方式分组:

Flux.just(1,2,3,4,5,6,7)
    .subscribe(n -> {
      if (n % 2 == 0) {
        System.out.println("Even stream value: " + n);
      } else {
        System.out.println("Odd stream value: " + n);
      }
    });

【讨论】:

  • 对于选项1和2,请检查它是否编译。 io.projectreactor 版本 3.4.12 出现编译错误
  • 是的,@samabcde 现在可以编译...
【解决方案2】:

正如@Michael Berry 所建议的,使用groupBy 是解决方案之一。
我们可以使用i % 2进行分组,返回一个Flux&lt;GroupedFlux&gt;,然后我们可以使用GroupedFlux#key()来区分奇数组或偶数组。

public class SplitFlux {
    public static void main(String[] args) {
        Flux.just(1, 2, 3, 4, 5, 6, 7).groupBy(i -> i % 2).toStream()
                .forEach(groupedFlux ->
                {
                    System.out.println(groupedFlux.key() == 0 ? "even" : "odd");
                    groupedFlux.toStream().forEach(System.out::println);
                });
    }
}

【讨论】:

  • 是的,已经尝试过了。但我需要对新的 Flux 做一个 repeat() 操作。无法在 GroupedFlux 上执行重复
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 2022-01-17
  • 2017-10-11
  • 2022-01-09
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多