The code snippet you gave is a bad example, the one who wrote it should have used the function.
Futures.transform () is used to track some asynchronous processes. Let's call it "ap1" for "asynchronous process 1". When ap1 is completed, the function encoded by the conversion will be executed. Now let's discuss two types of functions that you can associate using Futures.transform ().
// AsyncFunction() example: ListenableFuture<B> future2 = Futures.transform(future1, new AsyncFunction<A, B>() { public ListenableFuture<B> apply(A a) { if (a != null) { ListenableFuture<B> future3 = asyncCallToOtherService(a); return future3; } else { return Future.immediateFuture(null); } }); }); // more complex AsyncFunction() example: ListenableFuture<B> future2 = Futures.transform(future1, new AsyncFunction<A, B>() { public ListenableFuture<B> apply(A a) { if (a != null) { ListenableFuture<C> future3 = asyncCallToOtherService(a); return Futures.transform(future3, new Function<C, B>() { @Override public B apply(C c) { B b = new B(); b.setResult(c.getStatus()); return b; } }); } else { return Future.immediateFuture(null); } }); }); // Function() example: ListenableFuture<B> future2 = Futures.transform(future1, new Function<A, B>() { public B apply(A a) { if (a != null) { B b = new B(); b.setResult(a.getStatus()); return b; } else { return null; } }); });
- AsyncFunction () should be used when the code inside apply () creates another asynchronous process 2 (AP2). This forms a sequence of asynchronous calls that follow each other: AP1-> AP2.
- Function () should be used when converting the result from AP1 does not require additional asynchronous processes. Most likely, this synchronously translates the result of Object1 to another Object2.
- AsyncFunction () is a bit heavier and leads to a separate topic, so we should use function () when we do not need to rotate AP2.
- Multiple functions and AsyncFunctions can be combined together as needed to make a complete workflow. The example "more complex AsyncFunction () example" converts A ~> C-> B transforms, and A ~> C is asynchronous.
source share