Env: Akka 2.1, scala version 2.10.M6, JDK 1.7,u5
Now is my problem: I have:
future1 = Futures.future(new Callable<Future<object>>(){...}); future2 = ? extends Object; Future.sequence(future1, future2).onComplete(...)
now in first line, I have a future of Future of object, is there any way to convert it into a Future while not blocking my current thread?
Is there any method in akka? As far as I checked, I havn't found any yet... First time to have a post....Sry for bad format and organize... :~P
The future object can be used to check the status of a Callable and then retrieve the result from the Callable once the thread is done. It also provides timeout functionality.
Future<Void> is a future result of an execution that returns no value. That would be typically the result of invoking the run method of a Runnable .
NOTE: With Future. onComplete() we are no longer blocking for the result from the Future but instead we will receive a callback for either a Success or a Failure.
An example of using Future is working with Thread pools. When one submit a task to ExecutorService which is take a long running time, then it returns a Future object immediately. This Future object can be used for task completion and getting result of computation.
Short answer (English): flatMap dat sh!t
Shorter answer (Scala):
flatMap(identity)
Shortest answer: (Scala 2.12):
flatten
Long answer (Java):
flatMap(new Mapper<Future<X>>,Future<X>>() { @Override public Future<X> apply(final Future<X> f) { return f; } })
Note: Since Viktor Klang's 2012 answer, he recently (March 2016) added in his blog for scala 2.12:
flatten
Are you one of us
Future
-users who have grown tired of the oldflatMap(identity)
boilerplate for un-nesting Futures as in:
val future: Future[Future[X]] = ??? val flattenedFuture /*: Future[X] */ = future.flatMap(identity)
Then I have some great news for you! Starting with Scala 2.12
scala.concurrent.Future
will have a flatten-method with the following signature:
def flatten[S](implicit ev: T <:< Future[S]): Future[S]
Allowing you to write:
val future: Future[Future[X]] = ??? val flattenedFuture /*: Future[X] */ = future.flatten
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With