Last active
May 25, 2024 10:19
-
-
Save dacr/a57d62ebd0d0b3efabfaa5982fa27605 to your computer and use it in GitHub Desktop.
ZIO learning - zhttp - simple streaming / published by https://github.com/dacr/code-examples-manager #1dff6e7a-dd42-44c1-b04f-abb4c99cecae/5f76bd6811cd54dd07f9501e17f90c02fbaf01cd
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
// summary : ZIO learning - zhttp - simple streaming | |
// keywords : scala, zio, learning, pure-functional, http-server, zhttp, streams, @testable, @exclusive | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 1dff6e7a-dd42-44c1-b04f-abb4c99cecae | |
// created-on : 2024-01-05T18:37:43+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// test-with : curl http://127.0.0.1:8080/stream | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "dev.zio::zio-http:3.0.0-RC4" | |
// --------------------- | |
// inspired from https://github.com/zio/zio-http/issues/2284 | |
import zio.*, zio.http.*, zio.stream.* | |
object Main extends ZIOAppDefault { | |
override def run = | |
for { | |
hub <- Hub.unbounded[String] | |
_ <- ZIO.foreach(Range(1, 100))(i => hub.offer(s"$i\n").delay(500.millis)).fork | |
_ <- ZStream.fromHub(hub).run(ZSink.foreach(Console.print(_))).fork | |
stream = ZStream.fromHub(hub).flatMap(s => ZStream.fromIterable(s.getBytes)) | |
app = Routes(Method.GET / "stream" -> handler(Response(body = Body.fromStream(stream)))).toHttpApp | |
_ <- Server.serve(app).provide(Server.default) | |
} yield () | |
} | |
Main.main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment