Search code examples
scalafuturefor-comprehension

Ignore failing future in for comprehension


I have a for comprehension of futures that all make remote service calls (REST, RPC, etc...). If one of those future fails, will the entire for comprehension fail?

For instance, let's say I have two futures that make service calls

val service1Future: Future[Response] = ...
val service2Future: Future[Response] = ...

Let's say service2Future also has some recoverWith that throws an exception PartialFunction[Throwable, Future[U]].

If service2Future fails, I don't really care. Can I enforce that in my for comprehension?

for {
    service1Response <- service1Future
    service2Response <- service2Future
} yield {
    // do stuff with service1Response, but I want to get here even if service2Future fails
}

Solution

  • Yes, the entire for-comprehension will fail if the second future fails as written. Would something as simple as this work?

    for {
      service1Response <- service1Future
      service2Response <- service2Future.recoverWith(...)
    } yield {
      ...
    }