Search code examples
scalafor-loopfor-comprehension

How to wait for result of Scala Futures in for comprehension


I am having a issue with the below piece of code. I want 'combine' method to get triggered after all groundCoffee,heaterWater,frothedMilk method completes. They would be triggered concurrently.All the 4 methods grind,heatWater,frothMilk,brew are concurrently executed using a future.

def prepareCappuccino(): Future[Cappuccino] = {
  val groundCoffee = grind("arabica beans")
  val heatedWater = heatWater(Water(20))
  val frothedMilk = frothMilk("milk")
  for {
    ground <- groundCoffee
    water <- heatedWater
    foam <- frothedMilk
    espresso <- brew(ground, water)
  } yield combine(espresso, foam)
}

When I execute the above method the output I am getting is below

start grinding...
heating the water now
milk frothing system engaged!

And the program exits after this. I got this example from a site while I was trying to learn futures. How can the program be made to wait so that combine method get triggered after all the futures return?


Solution

  • You can use the Await here:

    val f = Future.sequence(futures.toList)
    Await.ready(f, Duration.Inf)
    

    I assume, you have all the futures packed in a list. The Await.ready makes all the waiting work.