I'm new to scala and I try to combine several Futures in scala 2.10RC3. The Futures
should be executed in sequential order. In the document Scala SIP14 the method andThen
is defined in order to execute Futures in sequential order. I used this method to combine several Futures
(see example below). My expectation was that it prints 6
but actually the result is 0
. What am I doing wrong here? I have two questions:
First, why is the result 0
. Second, how can I combine several Futures
, so that the execution of the second Future
does not start before the first Future
has been finished.
val intList = List(1, 2, 3)
val sumOfIntFuture = intList.foldLeft(Future { 0 }) {
case (future, i) => future andThen {
case Success(result) => result + i
case Failure(e) => println(e)
}
}
sumOfIntFuture onSuccess { case x => println(x) }
I like this generic approach:
Then mix-in the above trait and use it like this:
This code could be improved to preserve the input collection type. See this article for example.
andThen
is for side-effects. It allows you to specify some actions to do after future is completed and before it used for something else.Use map: