亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

CompletableFuture 包裝器

CompletableFuture 包裝器

皈依舞 2021-07-22 18:03:47
我有異步方法asyncClass.getChild("test", listChild -> {  if (listChild.isOk()) {  List<String> list = listChild.isSuccess().getData()  }  return null;});我如何在 CompletableFuture 中包裝這個異步調用?final CompletableFuture<List<String>> future = new CompletableFuture<>();asyncClass.getChild("test", listChild -> {  if (listChild.isOk()) {    future.complete(listChild.isSuccess().getData());  }  return null;});return future;一切正常,但我希望一切都在單獨的線程調用中工作interface AsyncFS {    fun getChild(path: String, onResult: (Result<List<String>>) -> Unit)}
查看完整描述

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;


查看完整回答
反對 回復 2021-07-29
?
胡說叔叔

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);

或使用他想要的任何執行程序進行任何其他處理。


如您所見,這比強制執行特定類型的回調要靈活得多。


查看完整回答
反對 回復 2021-07-29
?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

提供 Runnable 或 Supplier 作為參數CompletableFuture.runAsync()或supplyAsync()


return CompletableFuture.runAsync(() -> {

    doSomething();

}, optionalExecutor);


查看完整回答
反對 回復 2021-07-29
  • 3 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號