Skip to content

Instantly share code, notes, and snippets.

@saml
Last active December 18, 2015 10:19
Show Gist options
  • Save saml/5768192 to your computer and use it in GitHub Desktop.
Save saml/5768192 to your computer and use it in GitHub Desktop.
package tmp
import scala.concurrent.{Future, future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Try, Failure, Success}
/**
* author: saml
*/
object FutureTest {
private def plus1(x: Int): Future[Int] = future {
x + 1
}
private def maybeId(x: Int): Future[Int] = future {
val divisor: Int = if (x >= 2) 0 else 1
x / divisor
}
private def minus1(x: Int): Future[Int] = future {
if (x <= 0) throw new IllegalArgumentException("must be positive: " + x)
println(x)
x - 1
}
private def sequenceTry[A](x: Try[Future[A]]): Future[Try[A]] = x match {
case Success(a) => a.map(Success(_))
case Failure(err) => future(Failure(err))
}
def main(args: Array[String]) = {
def toFuture(x: Int): Future[Int] = for {
x1 <- plus1(x)
x2 <- maybeId(x1)
x3 <- minus1(x2)
} yield x3
def toMaybeFuture(x: Int): Future[Try[Int]] =
sequenceTry(Try(toFuture(x)))
val inputs: Seq[Int] = 0 until 10
val promiseResults: Future[Seq[Try[Int]]] = Future.traverse(inputs)(toMaybeFuture)
promiseResults.onComplete {
case Success(xs) => {
println("=== SUC " + xs.length)
println(xs)
}
case Failure(t) => {
println("=== ERR")
println(t)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment