Search code examples
spring-webfluxreactive

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.


Solution

  • 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;
                            }));
        }