猿问

什么是 Futures.transform() lambda 参数,以防原始 ApiFuture

我有一个异步发送消息列表的方法。每次发送都会返回ApiFuture<String>(GCP 版本的 Guava's ListenableFuture)。我需要这个方法来返回一个Future<Boolean>,所以我


在每个上创建列表依赖项 ApiFuture<String>

将结果ApiFuture<List<String>>转换为Future<Boolean>usingApiFutures.transform方法


ApiFuture< List < String > > allSentFuture = ApiFutures.allAsList(futures);

return ApiFutures.transform(allSentFuture, val -> { 

        return true; 

    }, 

    Executors.newCachedThreadPool()

);

我的问题是:val如果一个或多个原始期货失败/取消,上述 lambda的参数值是多少?在这种情况下甚至调用了 lambda 吗?


米脂
浏览 652回答 1
1回答

交互式爱情

ApiFuture<V>在 type 上形成一个monadV,transform并将一个函数应用于type的封装值V。如果由于失败或取消ApiFuture<V>而不包含V值,则转换后的未来是相同的。如果您想处理由于异常导致的失败,您可以使用ApiFutures.catching()来生成替代结果(例如Boolean.FALSE)。如果要将取消转换为成功值,我相信您需要ApiFuture.addListener直接使用,并让侦听器完成SettableApiFuture您返回的一个。然后侦听器(将在源未来被取消时被调用)可以检查isCancelled以检测这种情况,或者可以捕获并处理CancellationException.例如:/**&nbsp;* Adapt an iterable of {@link ApiFuture} instances into a single {@code ApiFuture}.&nbsp;*/static <T> ApiFuture<Boolean> adaptFutures(Iterable<ApiFuture<T>> futures) {&nbsp; &nbsp; final SettableApiFuture<Boolean> result = SettableApiFuture.create();&nbsp; &nbsp; final ApiFuture<List<T>> allFutures = ApiFutures.allAsList(futures);&nbsp; &nbsp; allFutures.addListener(&nbsp; &nbsp; &nbsp; &nbsp; () -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (allFutures.isCancelled()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.set(Boolean.FALSE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; allFutures.get();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.set(Boolean.TRUE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (ExecutionException | InterruptedException ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Maybe log something here?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Note that InterruptedException is actually impossible here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // because we're running in the listener callback, but the API&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // still marks it as potentially thrown by .get() above.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // So if we reach here it means that the allAsList future failed.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.set(Boolean.FALSE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; // Not normally safe, but we know our listener runs fast enough&nbsp; &nbsp; &nbsp; &nbsp; // to run inline on the thread that completes the last future.&nbsp; &nbsp; &nbsp; &nbsp; Runnable::run);&nbsp; &nbsp; return result;}
随时随地看视频慕课网APP

相关分类

Java
我要回答