CompletableFuture 包装器

我有异步方法


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)

}


皈依舞
浏览 155回答 3
3回答

手掌心

似乎asyncClass.getChild是异步执行的(因为它需要回调)。如果是这种情况,那么您当前的实现就足够了(下面的更正除外)。asyncClass.getChild("test", listChild -> {&nbsp; if (listChild.isOk()) {&nbsp; &nbsp; future.complete(listChild.isSuccess().getData());&nbsp; } else {&nbsp; &nbsp; &nbsp; future.complete(null); //you need to do this&nbsp; &nbsp; &nbsp; //or future.completeExceptionally(exception) if this is a failure&nbsp; }});如果您想getChild在单独的线程中运行,那么我强烈建议您重新设计该方法以使其返回List<String>而不是进行回调。这种设计使得getChild异步运行变得很尴尬。interface AsyncFS {&nbsp; &nbsp; fun getChild(path: String): List<String> //don't trust my syntax}然后以这种方式异步运行它:CompletableFuture<List<String>> future =&nbsp;&nbsp; &nbsp; CompletableFuture.supplyAsync(() -> asyncClass.getChild("test"));return future;

胡说叔叔

更改您的getChild()方法以返回 aCompletableFuture<ListChild>而不是将回调作为参数。没有实际的代码,我无法确切地说出这必须如何完成,但基本上代码看起来像CompletableFuture<ListChild> result = new CompletableFuture<>();processAsynchronously(path, result);return result;whereprocessAsynchronously()执行异步计算,并在某些时候调用result.complete(listChild).然后调用者将能够轻松地将调用链接起来,例如CompletableFuture<List<String>> result = asyncClass.getChild("test")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .thenAcceptAsync(listChild -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (listChild.isOk()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return listChild.isSuccess().getData()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, executor);或使用他想要的任何执行程序进行任何其他处理。如您所见,这比强制执行特定类型的回调要灵活得多。

饮歌长啸

提供 Runnable 或 Supplier 作为参数CompletableFuture.runAsync()或supplyAsync()return CompletableFuture.runAsync(() -> {&nbsp; &nbsp; doSomething();}, optionalExecutor);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java