Search code examples
reactive-programmingspring-webflux

How can I change T to Flux<T> for a controller's method's return type?


I have a method looks like this.

@GetMapping
Some read() {
    return getSome();
}

Now I want to change the result's type as a Mono as leave the getSome() non-reactive.

The question is which one is better? Or are they equivalent in the context of reactive system?

@GetMapping
Mono<Some> read() {
    return Mono.justOrEmpty(getSome()); // getSome() is still non-reactive
}

@GetMapping
Mono<Some> read() {
    return Mono.fromSupplier(() -> getSome()); // getSome() is still non-reactive
}

Solution

  • It's pretty much equivalent. However, Mono.fromSupplier is more readable in cases when the Mono value is produced by a Supplier:

    Mono.fromSupplier(this::getSome);
    

    Mono.justOrEmpty would be a good fit for something like this:

    Some some;
    Mono.justOrEmpty(some);