如何用Reactor风格实现短路循环?同步代码转Reactor示例
Convert Synchronous Short-Circuit Check to Reactor Style
Got it, let's translate that synchronous, short-circuiting checker logic into proper Reactor code while keeping all the original behavior intact. Here's the implementation of newWay():
public static Mono<String> newWay() { List<Checker> checkers = new ArrayList<>(); String param = "blahblah"; return Flux.fromIterable(checkers) // Use concatMap to preserve sequential execution (matches original for-loop order) .concatMap(checker -> checker.reactorCheck(param)) // Short-circuit as soon as any checker returns false .any(result -> !result) // Map the boolean result to our desired string output .map(hasFailedCheck -> hasFailedCheck ? "BAD" : "GOOD"); } interface Checker { boolean check(String str); Mono<Boolean> reactorCheck(String str); }
Key Details Explained:
concatMapinstead offlatMap: Your original code runs checks in sequence and short-circuits at the first failure.concatMapensures we execute eachreactorCheckone after another, and if the downstream operation (likeany) cancels early (when a failure is found), it stops running subsequent checks—perfectly mirroring the for-loop's behavior.any(result -> !result): This operator is short-circuiting. It will immediately emittrueas soon as it encounters afalseresult from any checker, and cancel the rest of the Flux. If all checkers pass (or the list is empty), it emitsfalse.- Final mapping: We convert the boolean outcome directly to "BAD" or "GOOD" to match the original method's return value.
This implementation maintains all the original logic (sequential execution, short-circuit on first failure, correct return values for empty lists) while being fully reactive.
内容的提问来源于stack exchange,提问作者chanjarster
相关产品推荐
相关产品推荐

