Search code examples
javareactive-programmingproject-reactorreactive-streams

Project Reactor: Designing a reactive API


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.


Solution

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

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