简体   繁体   English

理解动态期货列表:Scala

[英]For comprehension Dynamic List of Futures : Scala

I am trying to use for comprehension to execute list of futures in series. 我试图用于理解以执行一系列的期货清单。 The output of one future becomes input of the next future. 一个未来的输出成为下一未来的输入。 Below is the sample code. 下面是示例代码。

for {
      x <- plugins(0).execute(input)
      y <- plugins(1).execute(x)
      z <- plugins(2).excute(y)
    } yield z

The above code acts more like a waterfall, each plugins(i) executes on some input, and passes the output to next plugin. 上面的代码更像瀑布,每个插件(i)在某些输入上执行,然后将输出传递给下一个插件。 The output of the last plugin is the final output. 最后一个插件的输出是最终输出。 plugins is a Seq of Plugin object. plugins是一个Seq of Plugin对象。 The execute method returns a Future. execute方法返回Future。 I want to make the above code more generic, where the number of plugin in Plugins is dynamic. 我想使上面的代码更通用,其中Plugins中插件的数量是动态的。 How do i go about implementing it. 我该如何实施它。

plugins.foldLeft(Future.successful(input)) { (resultFuture, plugin) =>     
  resultFuture.flatMap(plugin.execute(_))
}

There are two tools in use here: foldLeft and flatMap 此处使用两种工具: foldLeftflatMap

Take a look at these links, and see if you understand what those functions do 查看这些链接,看看是否了解这些功能的作用

Future.successful just wraps input into a Future, so that we can treat it the same way we do all the other intermediate results. Future.successful只是将输入包装到Future中,以便我们可以像处理所有其他中间结果一样对待它。 Underscore is a shortcut for the lambda function parameter. 下划线是lambda函数参数的快捷方式。 Another way to write that piece would be: resultFuture.flatMap { result => plugin.execute(result) } . 编写该片段的另一种方法是: resultFuture.flatMap { result => plugin.execute(result) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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