[英]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. 如果要在回调具有嵌套回调之后执行某些操作。
CountDownLatch
or a ReentrantLock
that gets released when the function is run. CountDownLatch
或ReentrantLock
。 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));
andThen
method which you can use to run whatever is required post apply
. andThen
方法,您可以使用它运行后apply
所需的apply
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.