-1

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;
                    });
Melad Basilius
  • 3,847
  • 10
  • 44
  • 81
  • you could check the streams length with stream().count(). Which terminal operation do you use on the stream? – kosta.dani Oct 06 '21 at 09:31
  • Its been awhile, but I thought there was an "empty" Mono, failing that you have two options as I see it, return an `Optional` to indicate your method could return a value or not, or if its an error condition use `Error` i.e `Mono.error` – Gavin Oct 06 '21 at 09:34

1 Answers1

1

Try the following:

return externalClient.getExternalId()
                     .map(id -> {
                        entity.setExternalId(id);
                        return entity;
                     })
                     .switchIfEmpty(() -> {
                        entity.setExternalId(null);
                        return Mono.just(entity);
                     });
João Dias
  • 16,277
  • 6
  • 33
  • 45