5

Is there an operator or some good approach to achieve doOnEmpty() kind of behaviour with Project Reactor Mono?

I want to have side effects (logging) for operation result.

This is what I have now:

myMono
  .map(value -> new Wrapped(value))
  .defaultIfEmpty(new Wrapped(null))
  .doOnEach( ... )
  .flatMap(wrapped -> 
    wrapped.value == null ? 
      Mono.empty() : Mono.just(wrapped.value))

So I am wrapping actual value or in case of empty creating empty wrapper. Then the wrapper is consumed for side effects.

Instead using something like doOnEmpty(Consumer> signalConsumer) would be nice. To complicate things a bit more, I need to have access to the Signal in order to access the Context (contains data needed for the logging).

There are these answers but I don't think they apply or provide access to the Context.

So now that I think of this, maybe the proper question is:

"Is there a way to determine on doOnEach(Consumer Signal ) if observable resolved to empty?"

Raipe
  • 786
  • 1
  • 9
  • 22

1 Answers1

1

Some examples implementing "Empty Catch" with no side effect.

  • doOnSuccess - gets called with nullable result
Mono.empty()
    .doOnSuccess(result -> {
        if (result == null) {
            // This is an empty result
            Logger.info(this.getClass(), "result = {}", result);
        }
    })
    .subscribe();
  • switchIfEmpty + doOnError - skip pipe using throwning and catching known exception
Mono.empty()
    .switchIfEmpty(Mono.error(new Exception()))
    .doOnNext(o -> Logger.info(Object.class, "doOnNext"))
    .doOnError(Exception.class, error -> Logger.info(Exception.class, "doOnError"))
    .subscribe();
xIsra
  • 867
  • 10
  • 21
  • 1
    As described I need access to the `Signal` like it is provided on the `.doOnEach(Consumer super Signal> signalConsumer)`. I need be able to call `signal.getContext()`. `.doOnSuccess` does not provide access to context. – Raipe Nov 27 '20 at 07:02