Skip to content

Instantly share code, notes, and snippets.

@gaeljw
Last active October 11, 2018 12:39
Show Gist options
  • Save gaeljw/87a09b3b64b15153318adbd53c0e7d38 to your computer and use it in GitHub Desktop.
Save gaeljw/87a09b3b64b15153318adbd53c0e7d38 to your computer and use it in GitHub Desktop.
package utils
import scala.concurrent.{ExecutionContext, Future}
object FutureExt {
/**
* For each item in items, sequentially generate a future using futureGenerator to create a future for an item.
*
* @param items initial items
* @param futureGenerator function to generate a future for one item
* @param ec execution context
* @tparam T item type
* @tparam U future type
* @return a future containing the sequence of results
*/
def sequentially[T, U](items: Seq[T])(futureGenerator: T => Future[U])(implicit ec: ExecutionContext): Future[Seq[U]] = {
items.foldLeft(Future.successful(Seq[U]())) { (acc, item) =>
acc.flatMap { seq =>
futureGenerator(item).map(seq :+ _)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment