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);
添加回答
舉報