gpt4 book ai didi

java - 用于转换 future 的流利语法

转载 作者:行者123 更新时间:2023-11-29 04:30:21 25 4
gpt4 key购买 nike

我正在使用 Guava Futures将 future 的调用链接在一起。特别是我使用的是 Futures.transform(...)Futures.transformAsync(...) 的组合,但生成的代码可读性不是很好。有没有办法用更“流畅”的方式来表达同样的事情?

最佳答案

@ChrisPovirk mentioned in a comment上个月,一个流畅的包装器很快就会出现在公开的 Guava 中,现在它已经出现在 23.0-SNAPSHOT 中。

FluentFuture类用 @Beta 注释,所以即使 Guava 23.0 发布,它可能仍会发生变化。

无论如何,如果你现在 git clone Guava,你可以这样做:

ExecutorService executor = Executors.newFixedThreadPool(1);
// WARNING: based on UNRELEASED version, this is just to get a glimpse of the future... (Future... get it?) :o)
FluentFuture<String> f =
FluentFuture.from(immediateFuture("world"))
.transform(name -> "Hello " + name, directExecutor())
.transformAsync(input -> immediateFuture(input + "!"), executor);
System.out.println(f.get());

(令人惊奇的是,它打印出“Hello world!”)

关于java - 用于转换 future 的流利语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com