0

At some point in our code using rxjava we have

public Maybe<Event> verifyFoo(Event event){ return Maybe.just(event) .flatMap(this::foo) .doOnComplete(() -> logNotFound(event)); } private Maybe<Event> foo(Event event){ repository.findFooOrEmpty(event). .map(unused -> event); } private void logNotFound(Event event){ logger.warn("Foo not found for bar: ", event.getBar()); } 

Basically we want to know if something is in the repository, if it is keep going, if not do some side effect and return Maybe empty to stop the flow.

We are studying changing to reactor and to my surprise, Mono does not have doOnComplete. The closest thing I have found would be something like this:

public Mono<Event> verifyFoo(Event event){ return Mono.just(event) .flatMap(this::foo) .switchIfEmpty(Mono.defer(() -> logNotFound(priceEvent))); } private Mono<Event> foo(Event event){ repository.findFooOrEmpty(event). .map(unused -> event); } private Mono<Event> logNotFound(Event event){ logger.warn("Foo not found for bar: ", event.getBar()); return Mono.empty(); } 

But it doesn't feel right. So what would be a proper substitution for this case?

0

1 Answer 1

1

I think your only other option is to use doOnSuccess, which will be called when both onNext and onComplete are emitted upstream. So you end up with this:

public Mono<Event> verifyFoo(Event event) { return Mono.just(event) .flatMap(this::foo) .doOnSuccess(e -> logNotFound(e, event)); } private Mono<Event> foo(Event event) { repository.findFooOrEmpty(event). .map(unused -> event); } private void logNotFound(Event emitted, Event event) { if (emitted == null) { logger.warn("Foo not found for bar: ", event.getBar()); } } 

I'm not sure that it's significantly better than the switchIfEmpty option, though you're having to create fewer Mono instances this way.

I agree it's odd that doOnComplete is not implemented for Mono. I briefly searched but couldn't find any discussion about its omission, so I'm not sure if it's an oversight or a purposeful exclusion.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.