You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  • concatMap instead of flatMap: Your original code runs checks in sequence and short-circuits at the first failure. concatMap ensures we execute each reactorCheck one after another, and if the downstream operation (like any) 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 emit true as soon as it encounters a false result from any checker, and cancel the rest of the Flux. If all checkers pass (or the list is empty), it emits false.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:24:53