Skip to content

Instantly share code, notes, and snippets.

@kulikov
Last active December 5, 2017 13:45
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kulikov/af5eee983cc593a21ec8 to your computer and use it in GitHub Desktop.
object FutureHelpers {
def collectWhile[A, B](in: Seq[Future[A]])(pf: PartialFunction[A, B])(implicit ec: ExecutionContext): Future[Seq[B]] =
collectWhileImpl(in, pf, Seq.newBuilder[B]).map(_.result())
private def collectWhileImpl[A, B](in: Seq[Future[A]], pf: PartialFunction[A, B], buffer: mutable.Builder[B, Seq[B]])(implicit ec: ExecutionContext): Future[mutable.Builder[B, Seq[B]]] =
if (in.isEmpty) {
Future.successful(buffer)
} else {
in.head flatMap {
case r if pf.isDefinedAt(r) collectWhileImpl(in.tail, pf, buffer += pf(r))
case _ Future.successful(buffer)
}
}
}
"future takeWhile" in {
val input = Seq(Future(Option(1)), Future(Option(2)), Future(Option(3)), Future(None), Future(Option(5)), Future(Option(6)))
val out: Future[Seq[Int]] =
FutureHelpers.collectWhile(input) {
case Some(n) n
}
Await.result(out, 1 seconds) mustBe Seq(1, 2, 3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment