简体   繁体   English

等待异步回调函数在Java中返回

[英]Wait for the async callback function to return in java

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. 回调完成执行后,我想检查if(plugin.getIsInstalled().getValue()) How can I prevent execution of this if condition until callback has completed execution? 在回调完成执行之前,如何防止此条件的执行?

You can use a FutureTask that gets called in your callback function: 您可以使用在回调函数中调用的FutureTask

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. Future.get等待直到调用run方法,您还可以使用接受超时的get -method,以便在花费太长时间时对此做出反应。

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. 如果要在回调具有嵌套回调之后执行某些操作。

  1. You can use a CountDownLatch or a ReentrantLock that gets released when the function is run. 您可以使用在运行函数时释放的CountDownLatchReentrantLock
  2. Your foo#install can return a CompletableFuture and you can consume the results as follows 您的foo#install可以返回CompletableFuture ,您可以按以下方式使用结果
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 . 函数本身具有andThen方法,您可以使用它运行后apply所需的apply

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM