Question

I am new to Scala, and just start learning to use fully non-blocking nature of Scala API

I need to execute function after 2 tasks finish, curenly I do this following way:

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

val f1:Future[Int] = Future( {
    Thread.sleep(800)
    println(5)
    5
})

val f2: Future[Int] = Future( {
    Thread.sleep(500)
    println(6)
    6
})

val combined: Future[List[Int]] = Future.sequence(List(f1, f2))
combined.onComplete {
    case Success(li) => li.foldLeft(0)((sum, x) => sum + x)
    case Failure(t) => -1
}

Await.result(combined, 1 second)

Is there a more straight forward way to do this?

Was it helpful?

Solution

You can flatMap futures in for:

val f = for {
  r1 <- f1
  r2 <- f2
} yield (r1, r2) //any operations like `yield r1 + r2`

f.onSuccess { println }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top