chanjarster
chanjarster

Reputation: 526

How to write a shortcut loop in reactor fashion

I have a non-reactor fashion code like below, iterating over a list of checkers and shortcut return "BAD" if any checker return false:

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);
}

How can i convert code above to reactor fashion?

public static Mono<String> newWay() {
  // TODO
  return Mono.just("GOOD");
}

Upvotes: 0

Views: 76

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

Turn it on its head and use Flux#all(Predicate), but the input Flux is one of all the Checker you want to test:

//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();
}

Upvotes: 1

Related Questions