Last active
March 20, 2019 17:02
-
-
Save neilchaudhuri/dad25808fb17f28d28d452d2d7b8d477 to your computer and use it in GitHub Desktop.
Example of idiomatic Scala parallelism
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 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