Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data out of a Future in Scala

Tags:

scala

future

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]] = .... 
like image 935
Soumya Simanta Avatar asked Jun 04 '14 02:06

Soumya Simanta


2 Answers

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)
like image 58
Prasanna Avatar answered Nov 07 '22 08:11

Prasanna


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
}
like image 26
univerio Avatar answered Nov 07 '22 08:11

univerio