Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// see also https://www.implicitdef.com/2015/11/19/comparing-scala-http-client-libraries.html
// task: use the prime checker webservice
// https://github.com/LoyolaChicagoCode/primenumbers-spray-scala
// to count the number of primes within a given range
/* instructions: put the following lines in a build.sbt in a fresh folder:
scalaVersion := "2.12.10"
libraryDependencies += "com.typesafe.play" %% "play-ahc-ws-standalone" % "2.1.1"
*/
// then launch sbt console and paste the rest of the code in the resulting REPL
import scala.util.Success
import scala.concurrent.Future
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.libs.ws.ahc.StandaloneAhcWSClient
implicit lazy val system = ActorSystem("wsplay-example")
implicit val materializer = ActorMaterializer()
val wsClient = StandaloneAhcWSClient()
// List[Future[...]]
val urls = (10000000 to 10001000) map { n => "http://laufer-primechecker.herokuapp.com/" + n }
val requests = urls map { s => wsClient.url(s).get }
val results = requests map { f => f map { r => r.status == 200 } }
// Future[List[...]]
val f1 = Future.sequence(results)
val f2 = f1 map { r => r.count(identity) }
// print final result (in the background)
f2 foreach { v => println(v) }
// meanwhile, can check how many requests have completed
results.count(f => f.isCompleted)
// print wrapped result in the foreground
println(f2.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.