Created
August 26, 2020 13:38
-
-
Save adamw/6ee061b0c2567ca1d277f493c8d132d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 sttp.client.examples | |
import sttp.client._ | |
import sttp.client.asynchttpclient.fs2.AsyncHttpClientFs2Backend | |
import cats.effect.{ContextShift, IO} | |
import cats.instances.string._ | |
import fs2.{Stream, text} | |
import sttp.capabilities.fs2.Fs2Streams | |
object StreamFs2 extends App { | |
implicit val cs: ContextShift[IO] = IO.contextShift(scala.concurrent.ExecutionContext.global) | |
def streamRequestBody(backend: SttpBackend[IO, Fs2Streams[IO]]): IO[Unit] = { | |
val stream: Stream[IO, Byte] = Stream.emits("Hello, world".getBytes) | |
basicRequest | |
.streamBody(Fs2Streams[IO])(stream) | |
.post(uri"https://httpbin.org/post") | |
.send(backend) | |
.map { response => println(s"RECEIVED:\n${response.body}") } | |
} | |
def streamResponseBody(backend: SttpBackend[IO, Fs2Streams[IO]]): IO[Unit] = { | |
basicRequest | |
.body("I want a stream!") | |
.post(uri"https://httpbin.org/post") | |
.response(asStreamAlways(Fs2Streams[IO])(_.chunks.through(text.utf8DecodeC).compile.foldMonoid)) | |
.send(backend) | |
.map { response => println(s"RECEIVED:\n${response.body}") } | |
} | |
val effect = AsyncHttpClientFs2Backend.resource[IO]().use { backend => | |
streamRequestBody(backend).flatMap(_ => streamResponseBody(backend)) | |
} | |
effect.unsafeRunSync() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment