Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play! framework Java Promise example

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?

like image 752
user2635088 Avatar asked May 08 '15 15:05

user2635088


1 Answers

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.

like image 102
Mon Calamari Avatar answered Oct 05 '22 07:10

Mon Calamari