ps0604 ps0604 - 1 year ago 97
Scala Question

Conditional Future in Scala

Given these two futures, I need to run the first one only if a condition is true (see

if y>2
). But I get an exception
Future.filter predicate is not satisfied
. What does this mean and how to fix the example?

object TestFutures extends App {

val f1 = Future {

val f2 = Future {

val y = 1

val x = for {
x1 <- f1 if y>2
x2 <- f2
} yield x1 + x2


Answer Source

filter is not really something you should be able to do on a Future - what would a Future that didn't pass the condition return? From your example: we still need to have a value for x1 (even if it fails the if) to use in the yield x1 + x2.

Therefore, the filter method on Future is designed to fail hard when the predicate evaluates to false. It is an "assert" of sorts. You probably would prefer something like this (that provides a default value for x1 if the condition fails):

val x = for {
  x1 <- if (y > 2) f1 else Future.successful(/* some-default-value-for-x1 */)
  x2 <- f2
}  yield x1 + x2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download