Let's say I have a function func1
that needs to return a Future
with two integers. Each of the two values are returned by independent futures, like so:
def f1 = Future { 1 }
def f2 = Future { 2 }
def func1 : Future[(Int,Int)] = {
val future1 = f1
future1.map { result1 =>
result1 * 10
}
val future2 = f2
future2.map { result2 =>
result2 * 20
}
}
I need future1
wait until future2
ends (or vice versa) to return both results as (Int,Int)
. How can this be accomplished?
You can use a for-comprehension for futures that have already started like this:
If the futures were assigned to
lazy val
s ordefs
then this wouldn't work, because the futures would not have been started (if you start the futures inside the for comprehension, then they will be executed sequentially). Here is an example of starting them, and then waiting for them withfor
.Example:
Output:
In your case you could do this:
A
for
-comprehension is the best option here:More information can be found here and here.
Note: this will run the two
Future
s in sequence while Cyrille Corpet's solution will run them in parallel.That's precisely what the
zip
method on futures does:Note that if you haven't instantiated your futures before (say, if
future1
andfuture2
aredef
s, notval
s), this will run the two computations in parallel, while a for comprehension (orflatMap
) would wait for the first one to succeed before starting the second one.