Skip to content

Instantly share code, notes, and snippets.

@adamw
Created August 26, 2020 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamw/6ee061b0c2567ca1d277f493c8d132d1 to your computer and use it in GitHub Desktop.
Save adamw/6ee061b0c2567ca1d277f493c8d132d1 to your computer and use it in GitHub Desktop.
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