3 回答
TA贡献1942条经验 获得超3个赞
似乎asyncClass.getChild是异步执行的(因为它需要回调)。如果是这种情况,那么您当前的实现就足够了(下面的更正除外)。
asyncClass.getChild("test", listChild -> {
if (listChild.isOk()) {
future.complete(listChild.isSuccess().getData());
} else {
future.complete(null); //you need to do this
//or future.completeExceptionally(exception) if this is a failure
}
});
如果您想getChild在单独的线程中运行,那么我强烈建议您重新设计该方法以使其返回List<String>而不是进行回调。这种设计使得getChild异步运行变得很尴尬。
interface AsyncFS {
fun getChild(path: String): List<String> //don't trust my syntax
}
然后以这种方式异步运行它:
CompletableFuture<List<String>> future =
CompletableFuture.supplyAsync(() -> asyncClass.getChild("test"));
return future;
TA贡献1804条经验 获得超8个赞
更改您的getChild()方法以返回 aCompletableFuture<ListChild>而不是将回调作为参数。
没有实际的代码,我无法确切地说出这必须如何完成,但基本上代码看起来像
CompletableFuture<ListChild> result = new CompletableFuture<>();
processAsynchronously(path, result);
return result;
whereprocessAsynchronously()执行异步计算,并在某些时候调用result.complete(listChild).
然后调用者将能够轻松地将调用链接起来,例如
CompletableFuture<List<String>> result = asyncClass.getChild("test")
.thenAcceptAsync(listChild -> {
if (listChild.isOk()) {
return listChild.isSuccess().getData()
}
return null;
}, executor);
或使用他想要的任何执行程序进行任何其他处理。
如您所见,这比强制执行特定类型的回调要灵活得多。
TA贡献1951条经验 获得超3个赞
提供 Runnable 或 Supplier 作为参数CompletableFuture.runAsync()或supplyAsync()
return CompletableFuture.runAsync(() -> {
doSomething();
}, optionalExecutor);
添加回答
举报