igx
igx

Reputation: 4231

Scala mix list and futures in for comprehention

I want to mix list and futures in for comprehention

val list: List[Int] = List(1,2,3)
def f1(i: Int): Future[Boolean] = ???
def f2(i: Int): Future[List[Int]] = ???

looking at this answer this works fine if I wrap the list with future ans conver the f return type to List

import scalaz._
import ListT._
val x: Future[List[Boolean]] = (for {
  i <- listT(Future{ls})
  c <- listT(f2(i))
  b <- listT(f1(c).map(List(_)))
} yield b).run

The output that I am looking for should be Future[List[Boolean]]

however it seems inefficient with all this wrapping of the list with Future and convert boolean to list. and I had to use another library (scalaz)

any suggestions to simplify it?

Upvotes: 1

Views: 164

Answers (1)

C4stor
C4stor

Reputation: 8026

Using the Future.sequence operator to map Seq of Futures to Future of Seq :

val x: Future[List[Boolean]] = Future.sequence(list.map(f2)) // Change List[Future[List[Int]]] to Future[List[List[Int]]]
.map(_.flatten) // to Future[List[Int]]
.flatMap(list => Future.sequence(list.map(f1))) // map the new list when available to List[Future[Boolean]], and Future.sequence that to Future[List[Boolean]] !

Upvotes: 2

Related Questions