6
final Function<Boolean, ? extends Class<Void>> functionCallback = (Boolean t) -> {
   if(t) {
     plugin.setIsInstalled(Boolean.TRUE);             
   }
   return Void.TYPE;
};

foo.install(plugin,functionCallback);

if(plugin.getIsInstalled().getValue())
  return "done";
else 
  return "not done";

I want to check if(plugin.getIsInstalled().getValue()) once the callback has finished executing. How can I prevent execution of this if condition until callback has completed execution?

2
  • 1
    What is the return type of getIsInstalled? Commented Mar 12, 2019 at 17:03
  • 1
    BooleanProperty of javafx package. This property is set inside callback function which I want to access once callback has finished execution Commented Mar 12, 2019 at 17:05

3 Answers 3

7

You can use a FutureTask that gets called in your callback function:

final FutureTask<Object> ft = new FutureTask<Object>(() -> {}, new Object());
final Function<Boolean, ? extends Class<Void>> functionCallback = (Boolean t) -> {
    if(t) {
        plugin.setIsInstalled(Boolean.TRUE);
        ft.run();
    }
    return Void.TYPE;
};

foo.install(plugin,functionCallback); 
ft.get();
if(plugin.getIsInstalled().getValue())
    return "done";
else 
    return "not done";

Future.get waits till the run method was called, you can also use the get-method that accepts a timeout so you can react on that if it takes too long.

Sign up to request clarification or add additional context in comments.

Comments

3
  1. You can use a CountDownLatch or a ReentrantLock that gets released when the function is run.
  2. Your foo#install can return a CompletableFuture and you can consume the results as follows
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 1);
future.thenAccept((v) -> System.out.println("v = " + v));
  1. Function itself has an andThen method which you can use to run whatever is required post apply.

Comments

-1

The callback is mostly used to perform a task after a particular task is done. So it better separate the code you want to execute into a different function call that function.

If you want to execute something after callback have nested callbacks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.