Scala for comprehension responding Future.filter predicate is not satisfied

56 views Asked by At

I got the followin code

val obj1Seq: Future[Seq[Object1]] = /* call function returning Future[Seq[Object1]] */
val obj2Seq: Future[Seq[Object2]] = /* call function returning Future[Seq[Object2]] */
for {
  objects1 <- obj1Seq
  objects2 <- obj2Seq if (objects1.map(_.id) == objects2.map(_.relateObjId))
} yield {
  objects2
}

With this I want to get all the Object2 that the relatedObjId match the same id from the objects1 list

My problem is that I keep getting the error Future.filter predicate is not satisfied I have read few other questions here (this, this, this) and tried to adapt those solutions to my problem but I don't get to solved

2

There are 2 answers

0
ahabrahante On BEST ANSWER

This solve my problem

val result: Future[Seq[Object2]] = for {
  objects1 <- obj1Seq
  objects2 <- obj2Seq
} yield {
  for {
    obj1 <- objects1
    obj2 <- objects2 if obj1.id == obj2.relatedObjId
  } yield {
    obj2
  }
}

One of the things that made me uneasy with this problem is that the function that does this operation I only call it when I know that it will not return an empty list. Unfortunately I don't quite understand why and haven't had time to investigate further, if anyone has any idea how this works feel free to comment on this answer, thanks.

0
Gaël J On

The error you get is expected if the predicate (the sequence comparison) is not satisfied. I.e. you get a Future.failed with the said exception.

That's because Future#withFilter (which is called by the if in the for-comprehension) works like that. See scaladoc.


If I understand your need, your rather want something like this which always give a successful result (if both initial futures are successful):

val result: Future[Seq[Objects]] = for {
  objects1 <- obj1Seq
  objects2 <- obj2Seq
} yield {
  if (someCondition(objects1, objects2)) {
    // Some logic to get the desired results
    ???
  } else {
    Seq.empty
  }
}