javaproject-reactor

Unexpected return type of a reactive function


Consider the following code:

public static Mono<String> myFunction(boolean condition) {
    if (condition) {
        // returns Mono<String>
        return Mono.fromSupplier(() -> "Hello, World!"); 
    } else {
        // returns Mono<Void>  
        return Mono.fromRunnable(() -> System.out.println("Running a task...")); 
    }
}

This code compiles and run perfectly fine. Mono.fromSupplier returns String, whereas Mono.fromRunnable returns Mono<Void>, then ideally compilation should fail. What am I missing?


Solution

  • Mono.fromRunnable does not necessarily return Mono<Void>. In fact, it can return Mono<T> for any T.

    public static <T> Mono<T> fromRunnable(Runnable runnable)
    

    Because of type inference, it is inferred that you mean Mono.<String>fromRunnable(...).

    It creates an empty Mono<String> that completes without emitting any value. Think Mono.empty(), except it runs the Runnable on subscription.