Working with Scala Futures

Working with scala Futures is excellent for performance and non-blocking program flow. However, some conversions are slightly more tedious.

To add a completion action to a future, two non-blocking options exist. First, the Future can utilize a onSuccess (or onFailure / onComplete) call as shown below:


import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

val f1 = future {
Thread.sleep(10000)
println("Done")
}

f1 onSuccess {
case _ => println("After Done")
}

Second, the result (assumed successful) can be mapped to the next future result:


val f2 = future {
Thread.sleep(10000)
println("Done again, returning 1")
1
}

f2.map(number => println(10+number))

If a Seq of Futures is present, the result of all Futures may be relevant on how to proceed. This is where Future.sequence comes handy:


val futSeq = (1 to 10).map(i =>
future {
Thread.sleep(10000)
println("Done again, returning "+i)
i
}
)

val seqRes = Future.sequence(futSeq)
seqRes.map(s => println(s.sum))

Leave a comment