简体   繁体   中英

Multiple Futures in a Sequence in Scala

I have two computations that happen in a Future as below:

val comp1 = Future { ... }
val comp2 = Future { ... }

I want this to run such that comp2 always runs after comp1 has completed! I know that using a for expression, I can compose these two Future's like.

for {
  comp1Result <- comp1
  comp2Result <- comp2
} yield { ... }

What could be the guarantee that comp1 is completed before comp2? I mean these are computations that happen in a different thread and there is no guarantee to the order in which this might be run. Is there a way to guarantee order without blocking?

Scala for comprehensions are syntactic sugar for combinations of flatMap and map calls on the 'container type' (Futures, in this case), so your code above equates to:

comp1.flatMap{ comp1Result => comp2 }

the computation inside the curly braces here occurs only after comp1 completes and returns a successful result (in the case of failure, the internal computation doesn't get executed).

If you define comp2 outside of the for comprehension as shown in the question, you are kicking off that computation then (you just ignore the outcome until you're inside the for comprehension), but if you define it only inside the for comprehension, then it won't be kicked off unless and until comp1 completes successfully. So, try rejigging the code as follows:

val comp1 = Future { ... } // or you could put this construction inside the for as well
for {
  comp1Result <- comp1
  comp2Result <- Future { ... } // Only start the computation here
  comp3Result <- Future { ... } // etc. for as many such computations as you need
} yield { ... }

Other alternatives are to declare comp2 as a lazy val (so it isn't actually evaluated - kicking off the computation - until it is referenced), or as a lambda (eg val comp2 = () => Future { ... } ) and call it with the line

  comp2Result <- comp2()

inside the for comprehension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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