Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a void method in a Java Reactor chain?

Consider this code:

import reactor.core.publisher.Mono;

public class Main {

    public static void main(String[] args) {
        Mono.just(1)
            .map(Main::return_int) // is ok
//          .map(Main::return_void) // is not ok
            .subscribe();
    }

    private static void return_void(int input) {
        // do stuff with input
    }

    private static int return_int(int input) {
        return input;
    }
}

Obviously it's forbidden to use Mono#map with a void param, I get error: method map in class Mono<T> cannot be applied to given types; (...)

Now how can I call this method return_void() in a chain ?

Should I use another operator than #map? Or is there no other choice than wrapping return_void() into a method that returns Mono< Void> ?

like image 915
ThCollignon Avatar asked Jul 10 '19 07:07

ThCollignon


People also ask

How do you void a method in Java?

The void Keyword This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example.

Can we use void in Java?

It is a keyword and is used to specify that a method doesn't return anything. As the main() method doesn't return anything, its return type is void. As soon as the main() method terminates, the java program terminates too.

Why do we use void method in Java?

The void keyword specifies that a method should not have a return value.

How do you make mono void?

A void Mono is naturally empty. You can construct it with Mono. empty().


1 Answers

There is Mono#doOnNext that does not transform the flow, but allows you to perform side effects (something that returns void, as in your case)

Also, consider using Mono#handle to either proceed or call sink.error(...) when the value does not satisfy your condition instead of throwing from your void function.

like image 115
bsideup Avatar answered Sep 30 '22 14:09

bsideup