Reputation: 7735
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?
Upvotes: 0
Views: 119
Reputation: 1722
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 }
Upvotes: 4