j3d
j3d

Reputation: 9734

Scala: Conditional For-Comprehension with Futures

I need a for comprehension that invokes N methods that return a Future[Int] and yield only odd numbers. The following code doesn't work because after the first even result the block returns a Failure:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f1 = Future(1)
def f2 = Future(2)
def f3 = Future(3)
def f4 = Future(4)

for {
  i1 <- f1 if i1 % 2 != 0
  i2 <- f2 if i2 % 2 != 0
  i3 <- f3 if i3 % 2 != 0
  i4 <- f4 if i4 % 2 != 0
} yield ???

How do I get the following result?

List[Future(1), Future(3)]

Upvotes: 1

Views: 1047

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

Can something like this work instead?

val futures = List(f1, f2, f3, f4)
Future.sequence(futures).map(_.filter(_ % 2 != 0))

the result is

List(1, 3)

Upvotes: 4

Related Questions