Soumya Simanta
Soumya Simanta

Reputation: 11751

Getting data out of a Future in Scala

I've a Future[List[Person]][1] and I want to get the List[Person] from it. How can I do it ?

import scala.concurrent.Future
val futPersons : Future[List[Person]] = .... 

Upvotes: 5

Views: 4413

Answers (2)

Prasanna
Prasanna

Reputation: 3781

There are multiple ways:

futPersons.map { personList =>
  ....
}

This map returns another Future composed with whatever you return from the map. The map will execute only if the future completes successfully. If you need to handle failure you can use onComplete

futPersons.onComplete {
  case Success(personList) => ...
  case Failure(exception)  =>  ... 
}

Or you can wait for the future to complete (this is blocking):

val personList: List[Person] = Await.result(futPersons, 1 minutes)

Upvotes: 11

univerio
univerio

Reputation: 20548

Blocking way (pauses your thread until you get the value back) using Await.result:

scala.concurrent.Await.result(futPersons, timeout)

Or, using a callback with onSuccess:

futPersons onSuccess {
    case persons => // do something with persons
}

Upvotes: 3

Related Questions