2
votes

I have a map function which defined as follows: Mono<OUT> map(IN in)

Here's a concrete example:

public Mono<Integer> map(String s) {
            return Mono.fromCallable(() -> {
                try {
                    Thread.sleep(1_000); // simulate HTTP request
                    return 1;
                } catch (Exception e) {}

                return -1; // need to return something.
            });
        }

The problem is that in case of an error (i.e. IOException), we still need to return some output. There's also a possibility that there might no be an answer (but no error occurred)

One solution could be an Optional::empty but I think it's cumbersome. Preferably, I'd like to return Mono::empty if an error occurred.

The reason is, Mono::empty gets consumed by the subscriber without any further handling. Here's an example:

Flux.just(
                Mono.just("123"),
                Mono.empty(),
                Mono.just("456")
        ).flatMap(s -> s)
                .subscribe(System.out::println);

The output would be:

123
456

How can achieve the same behaviour?

What should map look like?

EDIT:
Rethinking it, maybe I better off return some container (like Optional) or a custom one (Result) which can be empty.

1
Why not return Mono.empty() inside the catch block? - uneq95
@uneq95, notice the try-catch is inside the Mono.fromCallable - yaseco
But you have not returned anything from the catch block. The return statement in your code snippet is outside the catch block. - uneq95
yeah, it could be inside the catch (doesn't really matter). The thing is, you must return something from the Callable, whereas I'd like to return a Mono::empty to the caller of map, in case there's no answer. - yaseco

1 Answers

4
votes

If I understand correctly, here's what you need:

return Mono.fromCallable(() -> {  
    Thread.sleep(1_000); // simulate HTTP request
    return 1;
}).onErrorResume(_ -> Mono.empty())