Search code examples
scalafor-comprehensionconcurrent.futures

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. The output of the last plugin is the final output. plugins is a Seq of Plugin object. The execute method returns a Future. I want to make the above code more generic, where the number of plugin in Plugins is dynamic. How do i go about implementing it.


Solution

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

    There are two tools in use here: foldLeft and flatMap

    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. Underscore is a shortcut for the lambda function parameter. Another way to write that piece would be: resultFuture.flatMap { result => plugin.execute(result) }.