简体   繁体   中英

How to conditionally execute Reactor's Mono/Flux supplier operator?

How to conditionally execute the then(Mono<T>) operator?

I have a method that returns Mono<Void> . It can also return an error signal. I want to use the then operator (or any other operator), only when the previous operation completes without an error signal.

Can someone help me to find the right supplier operator?

    public static void main(String[] args) {
        Mono.just("GOOD_SIGNAL")//It can also be a BAD_SIGNAL
                .flatMap(s -> firstMethod(s))
                .then(secondMethod())
                .subscribe()
        ;
    }
    private static Mono<String> secondMethod() {
        //This method call is only valid when the firstMethod is success
        return Mono.just("SOME_SIGNAL");
    }
    private static Mono<Void> firstMethod(String s) {
        if ("BAD_SIGNAL".equals(s)) {
            Mono.error(new Exception("Some Error occurred"));
        }

        return Mono
                .empty()//Just to illustrate that this function return Mono<Void>
                .then();
    }

-Thanks

then propagates an error in its source, so it covers this aspect. From what I understand, the reason you cannot use flatMap instead of then is that the source is empty, due to firstMethod() . In that case, combine defer() and then() to achieve the laziness you seek:

Mono.just("GOOD_SIGNAL")//It can also be a BAD_SIGNAL
    .flatMap(s -> firstMethod(s))
    .then(Mono.defer(this::secondMethod))
    .subscribe();

First of all, I want to underline that Reactor's Mono/Flux (will consider Mono next) have the following conditioning operators (at least what I know):

The second point is that Mono#then :

ignore element from this Mono and transform its completion signal into the emission and completion signal of a provided Mono. An error signal is replayed in the resulting Mono.

So it means that then is about to return the value (empty or provided) despite what was before it.

Considering all of that, your solution would look something like that:

public static void main(String[] args) {
        Mono.just("GOOD_SIGNAL")//It can also be a BAD_SIGNAL
                .flatMap(s -> firstMethod(s))
                .switchIfEmpty(secondMethod())
                .doOnError(...)//handle you error here
                .subscribe();
    }

private static Mono<String> secondMethod() {
     //This method call is only valid when the firstMethod is success
     return Mono.just("SOME_SIGNAL");
}

private static Mono<Void> firstMethod(String str) {
    return Mono.just(str)
               .filter(s -> "BAD_SIGNAL".equals(s))
               .map(s -> new Exception("Some Error occurred: "+s))
               .flatMap(Mono::error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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