javaspringwebflux

How to return null if the Mono is empty


I am calling an external service to get externalId, in case of that service doesn't work, all what i need is just populate the value with null

return externalClient.getExternalId() //returns Mono<String> or Mono.empty()
                    .map(id -> {
                        //in case of empty stream, i need call entity.setExternalId(null);
                        entity.setExternalId(id);
                        return entity;
                    });

Solution

  • Try the following:

    return externalClient.getExternalId()
                         .map(id -> {
                            entity.setExternalId(id);
                            return entity;
                         })
                         .switchIfEmpty(() -> {
                            entity.setExternalId(null);
                            return Mono.just(entity);
                         });