Play! framework Java Promise example
Asked Answered
P

1

6

I'm reading up on Java's Play framework but don't have much experience in Java. Can someone please explain this

Promise<Double> promiseOfPIValue = computePIAsynchronously();
Promise<Result> promiseOfResult = promiseOfPIValue.map(
  new Function<Double,Result>() {
    public Result apply(Double pi) {
      return ok("PI value computed: " + pi);
    }
  }
);

I get that they're creating a promise promiseOfPiValue that's supposed to compute a double asynchronously. Then, they call map on that instance of promise to which they're passing a new instance of Function as an argument, which has implemented a the apply method.

The map part is where I get lost - how does the map method work? It looks like its returning a new promise of type Result, but what's the logic of calling the apply method inside an implementation of Function?

Paediatrics answered 8/5, 2015 at 15:33 Comment(0)
T
3

From play documentation:

Maps this promise to a promise of type B. The function function is applied as soon as the promise is redeemed.

The function:

new Function<Double,Result>() {
    public Result apply(Double pi) {
      return ok("PI value computed: " + pi);
    }
}

will convert the pi value of type Double to Result using ok() function defined in Controller as soon as computePIAsynchronously is finished.

but what's the logic of calling the apply method inside an implementation of Function?

This is the beauty of Promises and Scala. Scala promise framework will make sure the function is applied when promise is redeemed. If you want to read up on this topic, I suggest grabbing sources and documentation of scala.concurrent.ExecutionContext.

Toffey answered 8/5, 2015 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.