Last active
August 29, 2015 14:01
-
-
Save Fristi/e7139a89e2c66d455e97 to your computer and use it in GitHub Desktop.
scalaz: Applicative for Future[T]. Does not sequentially await, but executes futures concurrently
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 java.util.concurrent.{Executors, TimeUnit} | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.{Await, ExecutionContext, Future} | |
import scalaz.Applicative | |
import scalaz.syntax.applicative._ | |
object Main extends App { | |
implicit def applicativeFuture(implicit executionContext:ExecutionContext) = new Applicative[Future] { | |
override def point[A](a: => A): Future[A] = Future.successful(a) | |
override def ap[A, B](fa: => Future[A])(f: => Future[(A) => B]): Future[B] = f.flatMap(fa.map(_)) | |
} | |
case class Test(x: Int, y: Int, z: Int) | |
def test(sleep: Int, value: Int)(implicit executionContext:ExecutionContext):Future[Int] = { | |
Future { | |
Thread.sleep(sleep) | |
value | |
} | |
} | |
override def main(args: Array[String]): Unit = { | |
implicit val ctx = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(3)) | |
val expr = (test(100, 1) |@| test(200, 2) |@| test(500, 3)) { Test.apply } | |
println(Await.result(expr, Duration.create(500, TimeUnit.MILLISECONDS))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment