简体   繁体   English

如何链接到Java 8供应商

[英]How to chain to a Java 8 Supplier

Supplier does not provide a andThen method, so chaining another Function to the result of a Supplier is not possible. Supplier不提供andThen方法,因此无法将另一个Function链接到Supplier的结果。 Is the only alternative to use a Function<Void, R> that does not get any parameter? 是否使用没有任何参数的Function<Void, R>的唯一选择?

In other words, if Supplier.andThen() existed I could write: 换句话说,如果Supplier.andThen()存在,我可以写:

 Supplier<Exception> cleanedExceptionSupplier = exceptionSupplier.andThen( 
     e -> clean(e));

Since it does not exist, how can I cleanly implement cleanedExceptionSupplier ? 由于它不存在,我如何干净地实现cleanedExceptionSupplier

Instead of: 代替:

 Supplier<T> supp2 = supp1.andThen(function);

(which, uses a method you've seen doesn't exist) (使用你见过的方法不存在)

... you could use: ......你可以用:

 Supplier<T> supp2 = () -> function.apply(supp1.get());

Just adding my alternate solution as a candidate here 在这里添加我的替代解决方案作为候选人

Function<Void, R> supplierAsFunction = v -> returnSomethingOfR();

supplierAsFunction.andThen(function).apply(null); 

Applying null as a parameter is rather ugly but this solution maintains functional style while using only java.util.function classes. null作为参数应用是相当丑陋的,但是这个解决方案在仅使用java.util.function类时保持了功能样式。

You may use CompletableFuture.supplyAsync(supplier) . 您可以使用CompletableFuture.supplyAsync(supplier) Having supplier that supplies object of type SomeType you will get CompletableFuture<SomeType> . 如果supplier提供SomeType类型的对象,您将获得CompletableFuture<SomeType>

Having CompletableFuture you may chain it using methods thenAccept , thenApply and other. 拥有CompletableFuture,您可以使用thenAcceptthenApply和其他方法链接它。

As a side effect, your program will become more reactive. 作为副作用,您的程序将变得更具反应性。 calling supplyAsync will not block. 调用supplyAsync不会阻止。 Actualy, you may never block as long as you will not call blocking operation on your CompletableFuture . 实际上,只要您不在CompletableFuture上调用阻止操作,您就永远不会阻止。

To I would solve your case as follows: 我将按如下方式解决您的情况:

Supplier<Exception> cleanedExceptionSupplier=<some way to get supplier>.
CompletableFuture.supplyAsync(cleanedExceptionSupplier).thenAccept(exception -> System.out.println(exception.toString());

Side note: it does not look right to me to have Supplier of Exception . 附注:我认为拥有Exception Supplier并不合适。 Is exception indeed main effect you want to supply? 您想要提供的例外确实是主要影响吗? Or is it (possibly unwanted) corner case? 或者是(可能不需要的)角落案例?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM