Caballero
Caballero

Reputation: 12091

Using result value of the future

Let's say I have this simple psedo example

val a: Future[String] = getValA //Assume asynchronous REST call
val b: String = getValB
val c: String = getValC

val d = a + b + c

//rest of the code

Now this obviously is not gonna work. I've looked into using future onComplete callback but that is not convenient for my case either, because it's return type is Unit and it is invoked as soon as future is available. Is there any other way to get the result value from the future except the callback?

For example if the future of val a is not complete by the time of val d expression, block it until complete, then use the value when it becomes available?

Upvotes: 0

Views: 71

Answers (1)

Tommi
Tommi

Reputation: 8608

You can use map, like this, to combine the values into a future:

val d: Future[String] = a.map { _ + b + c }

Or, if you absolutely must get the value right there, you can do a blocking call:

import scala.concurrent._
import scala.concurrent.duration._

val d: String = Await.result(a, 0 nanos) + b + c

Helpful reading: http://docs.scala-lang.org/overviews/core/futures.html

Upvotes: 3

Related Questions