Last active
November 10, 2017 12:09
-
-
Save phderome/217cebbffd1773f12bada4eba7766080 to your computer and use it in GitHub Desktop.
example of using traverse
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
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
case class fourData(a: Int, b: Int, c: Int, d: Int) | |
val computeListInputs: List[Int] = List(1,2,3,4) | |
def slowBlockingComputation(input: Int)(implicit ec: ExecutionContext): Future[Int] = { | |
// normally something non-trivial slow that could fail | |
Future.successful(input) // simulate that with trivial success | |
} | |
val out0 = Future.traverse(computeListInputs)(slowBlockingComputation) | |
val out1 = out0.map { | |
case a :: b :: c :: d :: Nil => Some(fourData(a+b, b+c, c+d, d+a)) | |
case _ => None | |
} | |
val out2 = Await.result(out1, 3 seconds) | |
out2 == Some(fourData(3,5,7,5)) | |
// Exiting paste mode, now interpreting. | |
warning: there was one feature warning; re-run with -feature for details | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
defined class fourData | |
computeListInputs: List[Int] = List(1, 2, 3, 4) | |
slowBlockingComputation: (input: Int)(implicit ec: scala.concurrent.ExecutionContext)scala.concurrent.Future[Int] | |
out0: scala.concurrent.Future[List[Int]] = Future(Success(List(1, 2, 3, 4))) | |
out1: scala.concurrent.Future[Option[fourData]] = Future(Success(Some(fourData(3,5,7,5)))) | |
out2: Option[fourData] = Some(fourData(3,5,7,5)) | |
res0: Boolean = true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
VKlang's comments on a linearize method on SO is also interesting as gist code assumes quite possibly wrongly the order of traverse's output list is same as input: https://stackoverflow.com/questions/44513544/does-future-traverse-ensure-the-order-of-execution