Search code examples
scalafutureakka-persistence

Turn a Future[Unit] into a Try[Unit] in Scala


I'm attempting to implement an API method (AsyncWriteJournal.asyncWriteMessages – part of Akka 2.4's persistence API) that requires me to return a Future[Seq[Try[Unit]]]. The idea being that a number of operations can be performed any of which may individually succeed or fail, the future can be used to await completion of all the operations. The future itself can optionally succeed even there's a certain class of failure in individual operations.

The underlying operations I'm using (Rediscala) return Futures but I'm stuck trying to transform a Seq[Future[Unit]] into the required return type. I can do it using Promise on each operation and tying them together with Future.sequence but then the resulting future fails if any of the operations fails which is not the correct behavior


Solution

  • Is this what you wanted?

    def transform(ops: Seq[Future[Unit]])(implicit ec: ExecutionContext): Future[Seq[Try[Unit]]] =
      Future.sequence(ops.map (
        _.map(Success(_)).recover {
          case ex => Failure(ex)
        }
      ))