简体   繁体   English

如果条件为真,则立即调用方法

[英]Calling a method immediately if the condition is true

I have an IStrategy interface as follows:我有一个 IStrategy 接口,如下所示:

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. IStrategy接口的每个实现调用不同的 WS。

For instance this is a Strategy1 :例如,这是一个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:这是在 add 方法中调用不同 WS 的另一个策略:

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.通过检查isApplicable方法,您可以确定要调用哪个add方法。

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.使用前面的代码片段,调用了所有isApplicable方法。 Then a single statement is applied to select the only iStrategy that respects the isApplicable .然后应用single语句来选择唯一符合 isApplicable 的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.我想调用isApplicable方法,如果它返回一个真正的 Mono,直接调用add方法,而不是先调用所有isApplicable(s) When an isApplicable method is true, the add method can be called immediately.isApplicable方法为 true 时,可以立即调用add方法。

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 . next()方法发出Flux发出的第一项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM