[英]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,您可以使用thenAccept
, thenApply
和其他方法链接它。
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.