Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono.zip with null

My code:

Mono.zip(
            credentialService.getCredentials(connect.getACredentialsId()),
            credentialService.getCredentials(connect.getBCredentialsId())
)
.flatMap(...

From the frontend we get connect object with 2 fields:

connect{
aCredentialsId : UUID //required
bCredentialsId : UUID //optional
}

So sometimes the second line credentialService.getCredentials(connect.getBCredentialsId())) can return Mono.empty

How to write code to be prepared for this empty Mono when my second field bCredentialsId is null?

What should I do? In case of empty values return Mono.just(new Object) and then check if obj.getValue != null??? I need to fetch data from DB for 2 different values

like image 750
Matley Avatar asked Oct 27 '25 10:10

Matley


1 Answers

The strategy I prefer here is to declare an optional() utility method like so:

public class Utils {

    public static <T> Mono<Optional<T>> optional(Mono<T> in) {
        return in.map(Optional::of).switchIfEmpty(Mono.just(Optional.empty()));
    }

}

...which then allows you to transform your second Mono to one that will always return an optional, and thus do something like:

Mono.zip(
        credentialService.getCredentials(connect.getACredentialsId()),
        credentialService.getCredentials(connect.getBCredentialsId()).transform(Utils::optional)
).map(e -> new Connect(e.getT1(), e.getT2()))

(...assuming you have a Connect object that takes an Optional as the second parameter of course.)

like image 141
Michael Berry Avatar answered Oct 30 '25 12:10

Michael Berry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!