The code snippet you gave is a bad example, whoever wrote it should have used Function.
Futures.transform() is used to follow up on some asynchronous process. Lets call it "ap1" for "asynchronous process 1". When ap1 is done, the function chained by transform will execute.
Now, lets discuss the 2 types of functions you can chain with 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 the apply() spawns another asynchronous process 2 (AP2). This forms a sequence of asynchronous calls that follow each other: AP1->AP2.
- Function() should be used when the transformation of the result from AP1 does not require any additional asynchronous processes. Rather all it does is translate the result Object1 into some other Object2 in a synchronous manner.
- AsyncFunction() is slightly heavier and results in separate thread, therefore we should use Function() whenever we don't need to spin AP2.
- Multiple Functions and AsyncFunctions can be chained together as needed in order to make a complete workflow. The example "more complex AsyncFunction() example" chains A~>C->B transformations, with A~>C being asynchronous.
a.getData
return? And what isB
? And what issomeFuture
? – InstrumentalityListenableFuture<B>
? – Instrumentality