Vandana
Vandana

Reputation: 81

Reactor 3 - How to return Flux on Mono Error?

Here is the boilerplate code: I want to do something like this -

public Flux<Object2> getSomething(String email) {
    method1(email).map(result -> {  //method1 returns Mono<Object1>
        if(result.id().isEmpty()) {
            return method2(email); //method2 returns Flux<Object2>
        } else {
            return Flux.empty();
        }
    };
});

So, when method1 returns an empty Object1.id(), then only call method2. Else return empty Flux.

Pointers to note are -

  1. It is not reaching the second method call

  2. Since one method is Mono and the other is Flux, there is a type mismatch if I directly add return in line 2.

  3. I tried with this in method1 :

    if(Object1.id().isEmpty()){
    
       throw new IllegalArgumentException;
    }
    

and in above code snippet :

try {
    method1(email);
} catch(IllegalArgumentException e) {
    return method2(email);
}

Never catches exception here.

Upvotes: 2

Views: 1939

Answers (2)

Vikram Rawat
Vikram Rawat

Reputation: 1662

You should use switchIfEmpty() operator.

Also, if you want to return both types (Mono as well as Flux) from the method then change the return type to org.reactiveStreams.Publisher. I will not recommend this though.

Rather return a Flux. Even if there is only 1 data to return then that can be returned as Flux nevertheless. Convert the Mono to Flux and if it empty user switchIfEmpty operator to send a different Flux Stream.

Upvotes: 1

Brian Clozel
Brian Clozel

Reputation: 59231

Your first code snippet should not compile since the method implementation is not retuning anything, so I'll try and guess what's happening.

Nothing happens here because the Publisher you're creating is not returned by the method. If nothing subscribes to that Flux/Mono, nothing happens.

public Flux<Object2> getSomething(String email) {
    return method1(email)
              .filter(result -> result.id().isEmpty())
              .flatMapMany(result -> method2(email));
}

Then you can use filter to filter out the result and not emit anything from that Mono if the predicate is not met. Also, flatMapMany will help you turn the result in the expected return type here.

Upvotes: 3

Related Questions