scala 我怎样才能将未来的未来变成一个未来的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11860910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:25:55  来源:igfitidea点击:

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

javascalasequenceakkafuture

提问by Vincent Zou

Env: Akka 2.1, scala version 2.10.M6, JDK 1.7,u5

环境:Akka 2.1,scala 版本 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?

现在在第一行,我有一个 Future of object 的未来,有什么方法可以将它转换为 Future 而不阻塞我当前的线程?

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

akka 有什么方法吗?据我检查,我还没有找到任何东西...第一次发帖....Sry格式错误并组织... :~P

回答by Viktor Klang

Short answer (English): flatMap dat sh!t

简答(英文): flatMap dat sh!t

Shorter answer (Scala):

更简短的答案(Scala):

flatMap(identity)

Shortest answer: (Scala 2.12):

最短的答案:(Scala 2.12):

flatten

Long answer (Java):

长答案(Java):

flatMap(new Mapper<Future<X>>,Future<X>>() {
  @Override public Future<X> apply(final Future<X> f) { return f; }
})

回答by VonC

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

注意:自从Viktor Klang的 2012 年回答以来,他最近(2016 年 3 月)在他的博客中scala 2.12添加

Missing canonical combinators: flatten

缺少规范组合器: flatten

Are you one of us Future-users who have grown tired of the old flatMap(identity)boilerplate for un-nesting Futures as in:

您是我们中的一员Future吗 - 已经厌倦flatMap(identity)了取消嵌套 Futures的旧样板的用户,例如:

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.Futurewill have a flatten-method with the following signature:

那么我有一个好消息要告诉你!从 Scala 2.12 开始,
scala.concurrent.Future将有一个带有以下签名的 flatten 方法:

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

回答by Peter Lawrey

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