你给出的代码片段是一个不好的例子,写它的人应该使用函数。
Futures.transform() 用于跟进一些异步过程。让我们将其称为“异步进程 1”的“ap1”。当 ap1 完成后,由 transform 链接的函数将执行。现在,让我们讨论可以与 Futures.transform() 链接的 2 种类型的函数。
// 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;
}
});
});
- 当 apply() 中的代码产生另一个异步进程 2 (AP2) 时,应使用 AsyncFunction()。这形成了一系列相互跟随的异步调用:AP1->AP2。
- 当从 AP1 转换结果不需要任何额外的异步过程时,应使用 Function()。相反,它所做的只是以同步方式将结果 Object1 转换为其他 Object2。
- AsyncFunction() 稍微重一些并且导致单独的线程,因此我们应该在不需要旋转 AP2 时使用 Function()。
- 可以根据需要将多个函数和 AsyncFunction 链接在一起,以形成完整的工作流程。示例“更复杂的 AsyncFunction() 示例”链接 A~>C->B 转换,其中 A~>C 是异步的。