简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM