概述

      本篇文章分享Flux.filter与Flux.filterWhen的异同,并进行了测试。

Flux.filter

JDK注释

      Evaluate each source value against the given Predicate. If the predicate test succeeds, the value is emitted. If the predicate test fails, the value is ignored and a request of 1 is made upstream.

翻译

      根据给定的断言计算Flux发出的每一个值,如果断言为真,就发出这个值,如果断言为假,则忽略这个值,然后再向上游请求一个值。

图示

在这里插入图片描述

代码测试

Flux.fromArray(fArray).filter(item ->{
   return item % 2 == 0;
}).next().subscribe(result ->{
   System.out.println(result);
});

Flux.filterWhen

JDK注释

      Test each value emitted by this Flux asynchronously using a generated Publisher test. A value is replayed if the first item emitted by its corresponding test is true. It is dropped if its test is either empty or its first emitted value is false.
      Note that only the first value of the test publisher is considered, and unless it is a Mono, test will be cancelled after receiving that first value. Test publishers are generated and subscribed to in sequence.

翻译

      Publisher异步测试每一个由Flux弹出的元素,如果Publisher的第一个元素测试为true,则重放这个元素,如果测试元素为空或者测试结果为false,则丢弃这个元素。
      注意,只有测试Publisher的第一个测试结果被采纳,除非它是Mono,接收Publisher的第一个测试结果后,余下的测试会取消,测试按照Publisher测试元素的顺序进行。

图示

在这里插入图片描述

代码测试

//测试一,结果2 4
Integer[] fwArray = new Integer[]{1,2,3,4};
Flux.fromArray(fwArray).filterWhen(item ->{
   return Mono.just(item % 2 == 0);
}).subscribe(result ->{
   System.out.println(result);
});

//测试二,结果 1 2 3 4,因为考虑Flux.just(true,false,false)
//的第一个值true
Flux.fromArray(fwArray).filterWhen(item ->{
   return Flux.just(true, false, false);
}).subscribe(result ->{
   System.out.println(result);
});

//测试三,结果空,因为考虑Flux.just(false, true, false)
//的第一个值false
Flux.fromArray(fwArray).filterWhen(item ->{
   return Flux.just(false, true, false);
}).subscribe(result ->{
   System.out.println(result);
});

总结

      filter与filterWhen都是测试一个值是否符合断言,不同点是断言的形式不同,filter直接接收一个断言,filterWhen接收一个Publisher类型的断言;Publisher类型的断言可以发出多个断言结果,但filterWhen只接收第一个。

Logo

尧米是由西云算力与CSDN联合运营的AI算力和模型开源社区品牌,为基于DaModel智算平台的AI应用企业和泛AI开发者提供技术交流与成果转化平台。

更多推荐