我有一个非反应器时尚代码,如下所示,遍历检查器列表,如果有任何检查器返回false,则快捷方式返回“ BAD”:
public static String oldWay() {
List<Checker> checkers = new ArrayList<>();
String param = "blahblah";
for (Checker checker : checkers) {
if (!checker.check(param)) {
return "BAD";
}
}
return "GOOD";
}
interface Checker {
boolean check(String str);
Mono<Boolean> reactorCheck(String str);
}
如何将上面的代码转换为反应堆样式?
public static Mono<String> newWay() {
// TODO
return Mono.just("GOOD");
}
答案 0 :(得分:1)
将其旋转并使用Flux#all(Predicate)
,但输入的Flux是要测试的所有Checker
之一:
//simplified Checker version for this example
interface Checker extends Predicate<String> {}
@Test
public void allChecks() {
//given the checks you want to apply, as a Flux<Checker>...
Checker lengthy = s -> s.length() > 3;
Checker startsWithA = s -> s.toUpperCase().startsWith("A");
Flux<Checker> checks = Flux.just(lengthy, startsWithA);
//...and given the param String you want to check...
String param = "Boooooh";
//... verify that _all_ checkers match the predicate that "param passes the checker"
Mono<String> allChecks = checks.all(checker -> checker.test(param))
//and map that result to GOOD or BAD
.map(allMatch -> allMatch ? "GOOD" : "BAD");
StepVerifier.create(allChecks)
.expectNext("BAD")
.verifyComplete();
//variant when multiple params to test:
Flux<String> params = Flux.just("Booooh", "Always", "Ace");
Flux<String> multiParamChecks = params.flatMap(p -> checks
.all(checker -> checker.test(p))
.map(valid -> p + (valid ? " GOOD" : " BAD"))
);
StepVerifier.create(multiParamChecks)
.expectNext("Booooh BAD")
.expectNext("Always GOOD")
.expectNext("Ace BAD")
.verifyComplete();
}