当第二阶段对第一阶段的结果值不感兴趣时​​,完成阶段链接 [英] CompletionStage chaining when 2nd stage is not interested in the 1st stage result value

查看:103
本文介绍了当第二阶段对第一阶段的结果值不感兴趣时​​,完成阶段链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

  • 有两个阶段
  • 第二阶段只有在第一阶段完成后才能执行
  • 第二阶段对第一阶段的结果不感兴趣,而只是对第一阶段的完成感兴趣

考虑现有方法:

public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);

它不能完全满足我的需要,因为该函数知道第一阶段结果值? super T

It doesn't quite satisfy my needs cause the function is aware of the 1st stage result value ? super T

我想拥有的东西是这样的:

What I would rather like to have is something like:

public <U> CompletionStage<U> thenApply(Supplier<? extends U> fn);

问题:我是否正确理解没有针对此问题的即用型解决方案,所以我必须编写自己的包装函数才能实现所需的行为?

Question: do I understand correctly that there's no out-of-the-box solution for that so I will have to write my own wrapper function in order to achieve the desired behavior?

推荐答案

没有这样的内置解决方案.但是您可以滥用" CompletableFuture.supplyAsync

There is no such built-in solution. But you could "abuse" CompletableFuture.supplyAsync and thenCompose:

Supplier<String> sup = ()->"s";
CompletableFuture.supplyAsync(()->4)
        .thenCompose(x->CompletableFuture.supplyAsync(sup))
        .thenAccept(System.out::println);

顺便说一句,我想可能没有这样的便捷方法,因为CompletionStage/CompletableFuture已经有很多方法了.

BTW, I guess probably there are no such convenience methods because CompletionStage/CompletableFuture already have quite many methods.

这篇关于当第二阶段对第一阶段的结果值不感兴趣时​​,完成阶段链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆