xxxxxxxxxx
val myFuture = Future {
// you have no future, you are DOOMED!
42
// JK.
}
The Scenario
xxxxxxxxxx
def gimmeMyPreciousValue(yourArg: Int): Future[String]
xxxxxxxxxx
object MyService {
def produceThePreciousValue(theArg: Int): String = "The meaning of your life is " + (theArg / 42)
def submitTask[A](actualArg: A)(function: A => Unit): Boolean = {
// send the function to be evaluated on some thread, at the discretion of the scheduling logic
true
}
}
-
A "production" function that is completely deterministic.
-
A submission function that has a pretty terrible API because the function argument will be evaluated on one of the service’s threads, and you can’t get the returned value back from another thread’s call stack.
xxxxxxxxxx
def gimmeMyPreciousValue(yourArg: Int): Future[String] = Future {
MyService.produceThePreciousValue(yourArg)
}
The Solution
xxxxxxxxxx
// create an empty promise
val myPromise = Promise[String]()
// extract its future
val myFuture = myPromise.future
// do your thing with the future, assuming it will be filled with a value at some point
val furtherProcessing = myFuture.map(_.toUpperCase())
xxxxxxxxxx
val asyncCall(promise: Promise[String]): Unit = {
promise.success("Your value here, your majesty")
}
How to Use it
def gimmeMyPreciousValue(yourArg: Int): Future[String] = {
// create promise now
val thePromise = Promise[String]()
// submit a task to be evaluated later, at the discretion of the service
// note: if the service is not on the same JVM, you can pass a tuple with the arg and the promise so the service has access to both
MyService.submit(yourArg) { x: Int =>
val preciousValue = MyService.producePreciousValue(x)
thePromise.success(preciousValue)
}
// return the future now, so it can be reused by whoever's consuming it
thePromise.future
}
failure
, trySuccess
/ tryFailure
and more.