In Futures.transform, what is the difference between using a Function and an AsyncFunction

SherinThomas picture SherinThomas · Jun 5, 2014 · Viewed 9.9k times · Source

I know that the apply method of Function returns an object synchronously, and the apply of AsyncFunction runs asynchronously and returns a Future.

Can you give me an example of when to prefer what.

One code snippet that I saw looked something like this:

Futures.transform(someFuture, new AsyncFunction<A, B>() {
  public B apply(A a) {
    if (a != null) {
      return Futures.immediateFuture(a.getData())
    } else {
      return Futures.immediateFailedFuture(checkException(());
    }
  });
});

Since the value inside AsyncFunction is returned as immediate result, why is AsyncFunction needed here? Or is this just a bad example that I came across?

Answer

Etienne Neveu picture Etienne Neveu · Jun 5, 2014

The code snippet you found is a bad example, since it uses an AsyncFunction for something that is computed synchronously. It's needlessly verbose.

The code would be cleaner using a standard Function:

Futures.transform(someFuture, new Function<A, B>() {
  public B apply(A a) {
    if (a != null) {
      return a.getData();
    } else {
      throw checkException();
    }
  });
});

You should use an AsyncFunction when the code that transforms A to B is asynchronous. In your example, it's possible that the code was asynchronous at first, and was later changed to use Futures.immediateFuture() / Futures.immediateFailedFuture() by a programmer who didn't bother replacing the AsyncFunction with a Function. Or maybe he just missed the overloaded method.