Last active
February 3, 2026 20:19
-
-
Save dacr/7b8cf68af09278b67b52b142bbccfc74 to your computer and use it in GitHub Desktop.
ZIO learning - implementing a backpressure queue / published by https://github.com/dacr/code-examples-manager #47acc4f4-4119-41b3-a337-a0999efa366c/1b22ea52b6e0377031528564894d59eced8cb5f0
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 - implementing a backpressure queue | |
| // keywords : scala, zio, learning, pure-functional, backpressure, queue, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 47acc4f4-4119-41b3-a337-a0999efa366c | |
| // created-on : 2021-04-06T15:32:12+02:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "dev.zio::zio:2.0.13" | |
| // --------------------- | |
| /* | |
| inspired from | |
| - [John A De Goes - ZIO: Next-Generation Effects in Scala](https://www.youtube.com/watch?v=mkSHhsJXjdc) | |
| - +39:00 | |
| */ | |
| import zio.* | |
| object Encapsulated extends ZIOAppDefault { | |
| // 500 producers, one consumer | |
| val logic = for { | |
| queue <- Queue.bounded[String](100) | |
| producers = (1 to 500).map(id => queue.offer(s"42 from $id").forever) | |
| fiber <- ZIO.forkAll(producers) | |
| consumer <- queue.take | |
| .flatMap(v => Clock.sleep(10.millis).flatMap(_ => Console.printLine(s"$v"))) | |
| .forever | |
| } yield () | |
| def run = logic.timeout(Duration.fromMillis(4000)) // Just to avoid this script to run infinitly... | |
| // back pressure is managed automatically for free !!!! | |
| } | |
| // ------------------------------------------------------------- | |
| Encapsulated.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment