为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 154 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信