Search code examples
javafunctional-interface

Functional interface that return void and passes a boolean parameter


I'm making a method to be executed in another thread because of the time it may take. However, I want to inform the caller that the operation iswill be finished and if it was successful. To do so, I would need a functional interface that returns nothing (I don't need the result of my callback) and that passes a boolean.

Example code:

public boolean send(Command command) {
    try {
        //long stuff
        return true;
    } catch(Exception ex) {
        //logging error
        return false;
    }
}

public void sendAsync(Command command, MyCallback callback) {
    new Thread(() -> {
        boolean successful = send(command);
        if(callback != null)
            callback.call(successful);
    }).start();
}

Something like:

void call(boolean successful);

Is it already present in Java or do I have to make one myself ?


Solution

  • The method void call(boolean successful) can be represented by a Consumer<Boolean> as void accept(Boolean b), which is built into java. That would allow you avoid having to make your own functional interface.

    Hence:

    public void sendAsync(Command command, Consumer<Boolean> callback) {
        new Thread(() -> {
            boolean successful = send(command);
            if(callback != null)
                callback.accept(successful);
        }).start();
    }