user3139545
user3139545

Reputation: 7374

Reactor 3 create MonoEmpty from a map function

What should the return value in a map function be for the resulting mono to be MonoEmpty?

example:

Mono<Void> empty = Mono.just("ping").map(s-> ????);

or should the pattern be to do a flatMap if I need this functionality?

Mono<Void> empty = Mono.just("ping").flatMap(s-> Mono.empty());

Upvotes: 0

Views: 105

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

If you need a transformation to take place most of the time, but be empty on some condition, use handle (which has the capacity to map to nothing without the overhead of flatMap):

Mono<String> emptyIfNotPing = Mono.just("ping")
        .handle((t, sink) -> {
            if (t.equals("ping")) sink.next("pong");
            else sink.complete();
        });

If you never care about the elements and just want to propagate terminal signals (onComplete and onError), you can either use ignoreElement (which maintains the generic type) or then() (which turns into a Mono<Void>):

Mono<String> source = Mono.just("foo");
Mono<Void> emptyWithTypeLoss = source.then();
Mono<String> emptyWithoutTypeLoss = source.ignoreElement();

Upvotes: 3

Related Questions