harry-potter
harry-potter

Reputation: 2059

Calling a method immediately if the condition is true

I have an IStrategy interface as follows:

public interface IStrategy {

    Mono<Tuple2<Response, String>> add(final String aString);
    Mono<Boolean> isApplicable(final String aString);
}

Then, there are a lot of classes that implement the previous interface. Each implementation of IStrategy interface calls a different WS.

For instance this is a Strategy1:

public class Strategy1 implements IStrategy {
    
    @Override
    public Mono<Boolean> isApplicable(String aString) {

     /*
         do some checks and returns 
         Mono.just(Boolean.TRUE) or 
         Mono.just(Boolean.FALSE)
     */

    @Override
    public Mono<Tuple2<Response, String>> add(String aString) {

     /*
           Calls WS 1 and returns a response
     */

     }
}

And this is another Strategy that calls a different WS in the add method:

public class Strategy2 implements IStrategy {
    
    @Override
    public Mono<Boolean> isApplicable(String aString) {

     /*
         do some checks and returns 
         Mono.just(Boolean.TRUE) or 
         Mono.just(Boolean.FALSE)
     */

    @Override
    public Mono<Tuple2<Response, String>> add(String aString) {

     /*
           Calls WS 2 and returns a response
     */

     }
}

By checking the isApplicable method, you can figure out which add method to call.

So, for instance:

List<IStrategy> strategiesList = new ArrayList<>(Arrays.asList(strategy1, strategy2, strategy3);

return Flux.fromIterable(strategiesList)
    .filterWhen(iStrategy -> iStrategy.isApplicable(aString))
    .single()
    .flatMap(iStrategy -> iStrategy.add(aString));

Using the previous snippet of code, all the isApplicable methods are called. Then a single statement is applied to select the only iStrategy that respects the isApplicable.

I would like to call the isApplicable method and if it returns a true Mono, make the call directly to the add method, without calling all the isApplicable(s) first. When an isApplicable method is true, the add method can be called immediately.

Upvotes: 0

Views: 950

Answers (1)

lkatiforis
lkatiforis

Reputation: 6255

This is what you are looking for:

return Flux.fromIterable(strategiesList)
    .filterWhen(iStrategy -> iStrategy.isApplicable(aString))
    .next()
    .flatMap(iStrategy -> iStrategy.add(aString));

The next() method emits the first item emitted by the Flux.

Upvotes: 1

Related Questions