Stephane Stephane - 2 months ago 7
Scala Question

Scala: from Seq to Sequential Futures

I have a

Seq
of
Book
that I need to save to my database in the same order they are in the Seq.
Book.save
returns a
Future[Unit]


If I write the following code, I know the save order may not be preserved:

books.map(_.save)


How can I sequentially execute these saves, but return the result as a
Future
?
Thanks!

Answer

You can use foldLeft:

val res:Future[Unit] = books.foldLeft(Future.successful {}) {
  case (acc, book) => acc.flatMap(_ => book.save)
}