How can I make A future of future into one future object?

血红的双手。 提交于 2019-11-27 13:46:21

问题


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


回答1:


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; }
})



回答2:


Note: Since Viktor Klang's 2012 answer, he recently (March 2016) added in his blog for scala 2.12:

Missing canonical combinators: flatten

Are you one of us Future-users who have grown tired of the old flatMap(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



回答3:


You can create another task

Futures.future(new Runnable(){
     // wait for future1
     // wait for future2
     // do something with the results.
});

or merge the tasks

Futures.future(new Runnable(){
     // do the work future2 would have done.
     // wait for future1
     // do something with the results.
});


来源:https://stackoverflow.com/questions/11860910/how-can-i-make-a-future-of-future-into-one-future-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!