madhairsilence
madhairsilence

Reputation: 3880

If else on Mono if empty or has value

This is the sample code

repo1.findById( id )
                .map( p -> {
                    if( p == null ){
                        return  repo2.findById( id ).flatMap( g -> {
                            g.setValue("some value");
                            return g;
                        });
                        
                    }
                    else{
                        return  repo3.findById( id ).flatMap( h -> {
                            h.setValue("some value");
                            return h;
                        });
                    }
                });

Any better way to do this ?. If else inside flat map does not look neat to me.

Upvotes: 3

Views: 3282

Answers (1)

Erunafailaro
Erunafailaro

Reputation: 1959

The idiomatic approach would be to use the switchIfEmpty() operator.

You would only proceed to use the call to repo3 if repo1 actually returns a result.

If not data matches repo1.findById(id), then this call would return an empty result, not null.

To cover this case, use switchIfEmpty().


public Mono<Data> load(String id){

        return repo1.findById(id)
                .flatMap(p -> {
                    return repo3.findById(id)
                            .flatMap(h -> {
                                h.setValue("some value");
                                return h;
                            });
                })
                .switchIfEmpty(repo2.findById(id)
                        .flatMap(g -> {
                            g.setValue("some value");
                            return g;
                        }));
    }

Upvotes: 2

Related Questions