Skip to content

Instantly share code, notes, and snippets.

@phderome
Last active November 10, 2017 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phderome/217cebbffd1773f12bada4eba7766080 to your computer and use it in GitHub Desktop.
Save phderome/217cebbffd1773f12bada4eba7766080 to your computer and use it in GitHub Desktop.
example of using traverse
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
@phderome
Copy link
Author

Wondering whether an approach of constructing an object (for instance a case class like fourData) using Future.traverse and map with pattern matching to be preferable over a traditional for comprehension approach.

@phderome
Copy link
Author

phderome commented Nov 10, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment