Conquest
Conquest

Reputation: 285

Wait for Future[List[Object]] to complete asynchronously in Scala

I have a Future[List[Object]] like

val futuresList: Future[List[Object]] = foo()

And I have another method which takes this futuresList and does some computations.

I want this future to complete execution before I can pass it to another method which returns a Future.

val futuresList: Future[List[Object]] = foo()
val anotherFuture: Future[Seq[Object]] = bar(futuresList, x, y)

Now I want to asynchronously wait for the futureList to complete, after which I want to pass it to bar()

So far I have tried this

futuresList.onComplete {
  case Success(data) => {  
    //call bar here, but how do I get access 'anotherFuture' ?
  }
}

Was hoping some guidance on how to access the response from bar() by making sure futuresList is complete. Thanks

Upvotes: 1

Views: 405

Answers (1)

PH88
PH88

Reputation: 1806

val anotherFuture = futuresList.flatMap(data => bar(Future.successful(data), x, y))

or if you prefer the for-comprehension syntax, which is equivalent:

val anotherFuture = for {
  data <- futuresList
} yield {
  bar(Future.successful(data), x, y)
} 

Upvotes: 1

Related Questions