Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Last active March 20, 2019 17:02
Show Gist options
  • Save neilchaudhuri/dad25808fb17f28d28d452d2d7b8d477 to your computer and use it in GitHub Desktop.
Save neilchaudhuri/dad25808fb17f28d28d452d2d7b8d477 to your computer and use it in GitHub Desktop.
Example of idiomatic Scala parallelism
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._
import play.api.libs.json._
implicit val system = ActorSystem()
system.registerOnTermination {
System.exit(0)
}
implicit val materializer = ActorMaterializer()
val ws = StandaloneAhcWSClient()
def getUuid: Future[String] = {
ws.url("https://httpbin.org/uuid")
.withHttpHeaders("Accept" -> "application/json")
.get
.map { response =>
(response.body[JsValue] \ "uuid").as[String]
}
}
val uuid1: Future[String] = getUuid
val uuid2: Future[String] = getUuid
val uuids = for {
u1 <- uuid1
u2 <- uuid2
} yield (u1, u2)
uuids
.map {
case (u1, u2) => println(s"UUIDs: $u1, $u2")
}
.andThen { case _ => ws.close() }
.andThen { case _ => system.terminate() }
.recover {
case t: Throwable => println(s"There was a problem: $t")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment