Last active
May 6, 2023 15:39
-
-
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/8cbe3436543c058766c75373278c97f9445d6b81
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
// summary : ZIO learning - implementing a backpressure queue | |
// keywords : scala, zio, learning, pure-functional, backpressure, queue, @testable | |
// 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 : 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.2.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