【问题标题】:Java Reactor flux filter with inner flux具有内部通量的 Java Reactor 通量过滤器
【发布时间】:2021-03-12 00:26:51
【问题描述】:

假设我有一个Flux<O>,我想过滤掉其中的一些,但这需要另一个Flux 的结果,不知道该怎么做。

例如


private Mono<Boolean> somePredicate(int num) {
   // logic
   return Mono.just(true);
}

Flux<O> flux = Flux.just(1, 2, 3, 4, ...);
flux.filter(n -> somePredicate(n));    // I know it is not right here, but could not figure out 

【问题讨论】:

    标签: java reactive reactor r2dbc


    【解决方案1】:

    你可以使用flatMap

            Flux<Boolean> booleanFlux = Flux.just(1, 2, 3, 4)
                    .flatMap(integer -> {
                        /*
                        or if you have a instance you can use method reference like this.
                        flatMap(swService::somePredicate)
                        */
                        return new MyClass().somePredicate(integer);
                    });
    
    
            booleanFlux.subscribe(aBoolean -> {
                System.out.println("aBoolean = " + aBoolean);
            });
    

    【讨论】:

      【解决方案2】:

      您可以使用 filterWhen 异步测试 Flux 发出的每个值:

      Flux.just( 1, 2, 3, 4).filterWhen( this::somePredicate );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-16
        • 1970-01-01
        • 2019-12-23
        • 2015-08-20
        • 2013-12-07
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        相关资源
        最近更新 更多