Last active
December 18, 2015 10:19
-
-
Save saml/5768192 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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