Last active
March 21, 2019 19:59
-
-
Save rzeigler/95a7d36bd15319f7a4d4724d8e94eae0 to your computer and use it in GitHub Desktop.
various ways of issuing requests
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
package com.github.rzeigler.reqs | |
import cats._ | |
import cats.implicits._ | |
import cats.effect._ | |
import cats.effect.implicits._ | |
import org.http4s.client.blaze._ | |
import org.http4s.client._ | |
import org.http4s.Uri | |
import cats.temp.par._ | |
import scala.concurrent.ExecutionContext | |
import cats.effect.Console.io | |
object Main extends IOApp { | |
val google = Uri.uri("https://www.google.com/") | |
val duck = Uri.uri("https://duckduckgo.com/") | |
def run(args: List[String]) = | |
BlazeClientBuilder[IO](ExecutionContext.global).resource | |
.use(client => | |
io.putStrLn("==== Serial ====") >> | |
serial(client).flatMap(io.putStrLn[(String, String)]) >> | |
io.putStrLn("==== Parallel ====") >> | |
parallel(client).flatMap(io.putStrLn[(String, String)]) >> | |
io.putStrLn("==== Parallel Explicit Fibers ====") >> | |
fiber(client).flatMap(io.putStrLn[(String, String)]) | |
) | |
.as(ExitCode.Success) | |
def serial[F[_]: Sync](client: Client[F]): F[(String, String)] = | |
client.expect[String](google).map(_.take(20)) | |
.product(client.expect[String](duck).map(_.take(20))) | |
def parallel[F[_]: Concurrent: Par](client: Client[F]): F[(String, String)] = | |
(client.expect[String](google).map(_.take(20)), client.expect[String](duck).map(_.take(20))) | |
.parMapN(_ -> _) | |
def fiber[F[_]: Concurrent](client: Client[F]): F[(String, String)] = { | |
client.expect[String](google).map(_.take(20)).start | |
.bracket(gFiber => | |
client.expect[String](duck).map(_.take(20)).start | |
.bracket(dFiber => | |
gFiber.join.product(dFiber.join) | |
)(_.cancel) | |
)(_.cancel) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment