Skip to content

Instantly share code, notes, and snippets.

@agaro1121
Last active January 31, 2017 15:23
Show Gist options
  • Save agaro1121/11d3de84bf305a3ff62d5b155d17dee6 to your computer and use it in GitHub Desktop.
Save agaro1121/11d3de84bf305a3ff62d5b155d17dee6 to your computer and use it in GitHub Desktop.
Create Future[Try[T]] from Future[T]
def mapValue[T]( f: Future[T] ): Future[Try[T]] = {
  val prom = Promise[Try[T]]()
  f onComplete prom.success
  prom.future
}

def traverseFilteringErrors[A, B](seq: Seq[A])(f: A => Future[B]): Future[Seq[B]] = {
  Future.traverse( seq )( f andThen mapValue ) map ( _ collect{ case Success( x ) => x } )
}

//usage:
traverseFilteringErrors(list)(mapValue)

//OR

def futureToFutureTry[T](f: Future[T]): Future[Try[T]] =
  f.map(Success(_)).recover { case t => Failure(t) }
  
//usage:
list map futureToFutureTry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment