SlideShare a Scribd company logo
Queue
Wiem Zine Elabidine
Milan Scala Group
Intro
Tour of ZIO
Intro
Tour of ZIO
Queue
Intro
Wrap up
Tour of ZIO
Queue
Intro
First point
John De Goes revealed the high performance of Scalaz8 Effect.
Motivation
The Scalaz8 effect is moved to a new
library Scalaz-zio with zero dependencies.
Good news!
What is ZIO?
ZIO provides purely functional data
structures with an abstraction for the
effectful programs using monads.
Effectful program
● Interaction with the real World
● Hard to reason about
● Hard to test
● Refactoring
● Programming without effects is useless
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
parseInt("Hello!")
[error] java.lang.NumberFormatException:
For input string: "Hello!"
NOT TOTAL!
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
addOne(10)
> 4
addOne(10)
> 6
addOne(10)
> 2
NON DETERMINISTIC!
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
SIDE EFFECT!
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
SIDE EFFECT!
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
def program(): = { }
Properties of pure functions
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
Pure functions
def parseInt(s: String): Option[Int] =
Try(s.toInt).toOption
def addOne(x: Int): Int = x + 1
def buyCoffee(cc: CreditCard): (Coffee, Charge) = {
val cup = new Coffee()
(cup, Charge(cc, cup.price))
}
def program(): = { }
Properties of pure functions
Pure functions
def parseInt(s: String): Option[Int] =
Try(s.toInt).toOption
def addOne(x: Int): Int = x + 1
def buyCoffee(cc: CreditCard): (Coffee, Charge) =
{
val cup = new Coffee()
(cup, Charge(cc, cup.price))
}
Non-pure functions
def parseInt(s: String): Int = s.toInt
def addOne(x: Int): Int = Random.nextInt(x) + 1
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
p.charge(cc, cup.price)
cup
}
def program(): = { } def program(): = { }
Properties of pure functions
● Total
● Deterministic
● Free of side effects
TOUR OF
What is IO[E, A] ?
IO is an immutable data structure that describes an
effectful program that may:
● fail with an E
● run forever
● produce a single A
What is IO[E, A] ?
parseInt("hello") //fails with NumberFormatExceptionIO.syncException(parseInt(str))
What is IO?
parseInt("1")IO.syncException(parseInt(str))
What is IO[E, A] ?
println("Hello!")IO.sync(println("Hello!")
What is IO[E, A] ?
throw new Exception("error")IO.fail(new Exception("error"))
What is IO[E, A] ?
while(true) {}IO.never
IO[E, A] structure
trait IO[E, A] { self =>
def map[B](f: A => B): IO[E, B]
def flatMap[E, B](f0: A => IO[E, B]): IO[E, B]
...
}
object IO {
def fail[E](error: E): IO[E, Nothing] = ???
def now[A](a: A): IO[Nothing, A] = ???
...
}
IO[E, A]
IO Effects
IO describes the following effects:
● Pure Values
val number: Int= 1
val number: IO[Nothing, Int] = IO.now(1)
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
println("hello")
val putStrLn: IO[Nothing, Unit] =
IO.sync(println("hello"))
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
parseInt("hello")
val toInt: IO[Throwable, Int] =
IO.syncThrowable(parseInt("hello"))
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
parseInt("hello")
val toInt: IO[Exception, Int] =
IO.syncException(parseInt("hello"))
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
parseInt("hello")
val toInt: IO[String, Int] =
IO.syncCatch(parseInt("hello")){
case e: NumberFormatException => "oh no!"
}
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
● Asynchronous Effects
Future(4)
IO.async[Nothing, Int](_(Completed(4)))
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
● Asynchronous Effects
● Concurrent Effects
val hello = new Thread(new Runnable {
def run() {
while (true) {
println("hello world")
}
}
})
for {
f <- IO.sync(println("hello world")).fork
_ <- f.join
} yield ()
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
● Asynchronous Effects
● Concurrent Effects
val hello = new Thread(new Runnable {
def run() {
while (true) {
println("hello world")
}
}
})
for {
f <- IO.sync(println("hello world")).forever.fork
_ <- f.interrupt
} yield ()
IO Effects
IO describes the following effects:
● Pure Values
● Synchronous Effect
● Asynchronous Effects
● Concurrent Effects
● Resource Effects
val f: File = openFile()
try {
compute(f)
}
finally {
closeFile(f) //Unit
}
IO.bracket[Error, File, Unit](openFile())
(f => closeFile(f))(f => compute(f))
Usage of IO
In ZIO, every type has specific
features to solve different problems.
Each type is wrapped inside an IO.
Promise[E, A]
Ref[A]
Queue[A]
IO[E, A]
RTS: IO runtime system
IO is interpreted by the IO runtime system into
effectful interactions with the external world.
● unsafeRun
● In your application’s main function (App
provides this functionality automatically).
def main(args: Array[String]): Unit =
println("Hello")
def main(args: Array[String]): Unit =
unsafeRun(IO.sync(println("Hello")))
Ref
Ref is the equivalent of `var`
Ref has an AtomicReference to apply the
atomic operations on it.
Ref
Ref[A]
object Ref {
def apply[A](a: A): IO[Nothing, Ref[A]] = ???
}
trait Ref[A] {
def get: IO[Nothing, A]
def set(a: A): IO[Nothing, Unit]
def update(f: A => A): IO[Nothing, A]
def modify[B](f: A => (B, A)): IO[Nothing, B]
}
Example
for {
counter <- Ref(0)
v <- counter.update(_ + 1)
} yield v
for {
counter <- Ref(0)
v <- counter.modify {
prev =>
val newValue = prev + 1
(s"previous value: $prev, next value is: $newValue", newValue)
}
_ <- IO.sync(println(v))
} yield ()
Promise
A Promise is an asynchronous variable that
can be set only once.
Promise
A Promise is an asynchronous variable that
can be set only once.
`error`: fails the promise with the specified error, which will be
propagated to all fibers waiting on the value of promise.
Promise
A Promise is an asynchronous variable that
can be set only once.
`complete`: completes the promise with the specified value.
Promise
By default the state of Promise is Pending, once it fails or completes
the state changes to Done.
`done`: completes the promise with the specified result.
A Promise is an asynchronous variable that
can be set only once.
Promise
trait Promise[E, A] {
def get: IO[E, A]
def complete(a: A): IO[Nothing, Boolean]
def error(e: E): IO[Nothing, Boolean]
def interrupt(t: Throwable): IO[Nothing, Boolean]
def done(r: ExitResult[E, A]): IO[Nothing, Boolean]
}
Promise[E, A]
object Promise {
def make[E, A]: IO[Nothing, Promise[E, A]] = ???
}
Promise: Example
Get an alert for your friends’s
birthday, as follow up reminder to
offer the appropriate “happy
birthday” greeting.
🎂
Promise: Example
(for {
p <- Promise.make[Nothing, String]
_ <- p.complete(s"Your reminder for ${friend.name} birthday")
.delay(minus(LocalDate.now, friend.birthday))
.fork
msg <- p.get
} yield sendAlert(msg)).fork
20.12.2018
QUEUE
Queue
Queue is an asynchronous queue which allows to
add and remove elements in First In First Out
manner.
...
V6
V5
V4
V3
V2
V1
offer* take*
Queue
Producers Consumers
trait Queue[A] {
def take: IO[Nothing, A]
def takeAll: IO[Nothing, List[A]]
def takeUpTo(max: Int): IO[Nothing, List[A]]
def offer(a: A): IO[Nothing, Boolean]
def offerAll(as: Iterable[A]): IO[Nothing, Boolean]
}
object Queue {
def bounded[A](capacity: Int): IO[Nothing, Queue[A]]
def unbounded[A]: IO[Nothing, Queue[A]]
def sliding[A](capacity: Int): IO[Nothing, Queue[A]]
def dropping[A](capacity: Int): IO[Nothing, Queue[A]]
}
Queue[A]
Queue
Takers
take
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
Takers
take
take
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
v2 <- queue.take.fork
Takers
take
take
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
v2 <- queue.take.fork
_ <- queue.offer("hello").fork
“hello”
Producers
Takers
take
take
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
v2 <- queue.take.fork
_ <- queue.offer("hello").fork
_ <- queue.offer("bye").fork
Producers
“hello”
“bye”
Takers
take
take
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
v2 <- queue.take.fork
_ <- queue.offer("hello").fork
_ <- queue.offer("bye").fork
Producers
“bye”
“hello”
Takers
Consumers
for {
queue <- Queue.unbounded[String]
v1 <- queue.take.fork
v2 <- queue.take.fork
_ <- queue.offer("hello").fork
_ <- queue.offer("bye").fork
} yield ()
Producers
“hello”
“bye”
Back pressure
A bounded Queue with capacity = 3
for {
queue <- Queue.bounded[String](3)
Back pressure
“b”
“c”
“a”
“d”
“b”
“c”
Producers
for {
queue <- Queue.bounded[String](3)
_ <- queue.offer("a").fork
_ <- queue.offer("b").fork
_ <- queue.offer("c").fork
_ <- queue.offer("d").fork
Back pressure
“c”
“b”
“a”
offer(“d”)
Producers
for {
queue <- Queue.bounded[String](3)
_ <- queue.offer("a").fork
_ <- queue.offer("b").fork
_ <- queue.offer("c").fork
_ <- queue.offer("d").fork
Back pressure
take
offer(“d”)
ConsumersProducers
for {
queue <- Queue.bounded[String](3)
_ <- queue.offer("a").fork
_ <- queue.offer("b").fork
_ <- queue.offer("c").fork
_ <- queue.offer("d").fork
v1 <- queue.take.fork
“c”
“b”
“a”
Back pressure
“c”
“b”
offer(“d”)
Consumers
“a”
Producers
for {
queue <- Queue.bounded[String](3)
_ <- queue.offer("a").fork
_ <- queue.offer("b").fork
_ <- queue.offer("c").fork
_ <- queue.offer("d").fork
v1 <- queue.take.fork
Back pressure
“d”
“c”
“b”
ConsumersProducers
for {
queue <- Queue.bounded[String](3)
_ <- queue.offer("a").fork
_ <- queue.offer("b").fork
_ <- queue.offer("c").fork
_ <- queue.offer("d").fork
v1 <- queue.take.fork
} yield ()
Sliding
for {
queue <- Queue.sliding[String](3)
_ <- queue.offer("A") //(1)
} yield ()
Sliding
for {
queue <- Queue.sliding[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
} yield ()
Sliding
for {
queue <- Queue.sliding[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("C") //(3)
} yield ()
Sliding
for {
queue <- Queue.sliding[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("C") //(3)
_ <- queue.offer("D") //(4)
} yield ()
Sliding
for {
queue <- Queue.sliding[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("C") //(3)
_ <- queue.offer("D") //(4)
} yield ()
Dropping
for {
queue <- Queue.dropping[String](3)
_ <- queue.offer("A") //(1)
} yield ()
Dropping
for {
queue <- Queue.dropping[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
} yield ()
Dropping
for {
queue <- Queue.dropping[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("C") //(3)
} yield ()
Dropping
for {
queue <- Queue.dropping[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("C") //(3)
_ <- queue.offer("D") //(4)
} yield ()
Dropping
for {
queue <- Queue.dropping[String](3)
_ <- queue.offer("A") //(1)
_ <- queue.offer("B") //(2)
_ <- queue.offer("D") //(4)
} yield ()
Shutdown
for {
queue <- Queue.unbounded[String]
_ <- queue.offer("A").forever.fork
_ <- queue.take.forever.fork
} yield ()
Shutdown
for {
queue <- Queue.unbounded[String]
_ <- queue.offer("A").forever.fork
_ <- queue.take.forever.fork
_ <- queue.shutdown
} yield ()
Shutdown
for {
queue <- Queue.unbounded[String]
_ <- queue.offer("A").forever.fork
_ <- queue.take.forever.fork
_ <- queue.shutdown
} yield ()
Wrap up
Wrap Up
github.com/scalaz/scalaz-zio
Wrap Up
https://gitter.im/scalaz/scalaz-zio/
https://javadoc.io/doc/org.scalaz/scalaz-zio_2.12/0.5.1
https://scalaz.github.io/scalaz-zio/
Thank you
@WiemZin
wi101

More Related Content

What's hot

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
John De Goes
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
GlobalLogic Ukraine
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
Luka Jacobowitz
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
Oliver Daff
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
The Software House
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
Hermann Hueck
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
Luka Jacobowitz
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
Chiwon Song
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
The Software House
 
Scalaz
ScalazScalaz
Scalaz
mpilquist
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
Shai Geva
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
saintiss
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
Luka Jacobowitz
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 

What's hot (20)

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Scalaz
ScalazScalaz
Scalaz
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
 
ppopoff
ppopoffppopoff
ppopoff
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 

Similar to ZIO Queue

What are monads?
What are monads?What are monads?
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
Philip Schwarz
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019
Daniel Pfeiffer
 
Functional IO and Effects
Functional IO and EffectsFunctional IO and Effects
Functional IO and Effects
Dylan Forciea
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
Daniel Sebban
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
Fabernovel
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
Romain Lecomte
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aid
David Hoyt
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
Hermann Hueck
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
PuneetChaturvedi23
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
Dallas Scala Meetup
Dallas Scala MeetupDallas Scala Meetup
Dallas Scala Meetup
Abhishek Srivastava
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
John De Goes
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Aspect-Oriented Technologies
Aspect-Oriented TechnologiesAspect-Oriented Technologies
Aspect-Oriented Technologies
Esteban Abait
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
Jorge Vásquez
 

Similar to ZIO Queue (20)

What are monads?
What are monads?What are monads?
What are monads?
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019
 
Functional IO and Effects
Functional IO and EffectsFunctional IO and Effects
Functional IO and Effects
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aid
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
 
Dallas Scala Meetup
Dallas Scala MeetupDallas Scala Meetup
Dallas Scala Meetup
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
Aspect-Oriented Technologies
Aspect-Oriented TechnologiesAspect-Oriented Technologies
Aspect-Oriented Technologies
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 

Recently uploaded

Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 

Recently uploaded (20)

Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 

ZIO Queue

  • 5. Wrap up Tour of ZIO Queue Intro
  • 6. First point John De Goes revealed the high performance of Scalaz8 Effect.
  • 8. The Scalaz8 effect is moved to a new library Scalaz-zio with zero dependencies. Good news!
  • 9. What is ZIO? ZIO provides purely functional data structures with an abstraction for the effectful programs using monads.
  • 10. Effectful program ● Interaction with the real World ● Hard to reason about ● Hard to test ● Refactoring ● Programming without effects is useless
  • 11. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup }
  • 12. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } parseInt("Hello!") [error] java.lang.NumberFormatException: For input string: "Hello!" NOT TOTAL!
  • 13. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup }
  • 14. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } addOne(10) > 4 addOne(10) > 6 addOne(10) > 2 NON DETERMINISTIC!
  • 15. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup }
  • 16. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } SIDE EFFECT!
  • 17. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } SIDE EFFECT!
  • 18. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } def program(): = { }
  • 19. Properties of pure functions Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } Pure functions def parseInt(s: String): Option[Int] = Try(s.toInt).toOption def addOne(x: Int): Int = x + 1 def buyCoffee(cc: CreditCard): (Coffee, Charge) = { val cup = new Coffee() (cup, Charge(cc, cup.price)) } def program(): = { }
  • 20. Properties of pure functions Pure functions def parseInt(s: String): Option[Int] = Try(s.toInt).toOption def addOne(x: Int): Int = x + 1 def buyCoffee(cc: CreditCard): (Coffee, Charge) = { val cup = new Coffee() (cup, Charge(cc, cup.price)) } Non-pure functions def parseInt(s: String): Int = s.toInt def addOne(x: Int): Int = Random.nextInt(x) + 1 def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() p.charge(cc, cup.price) cup } def program(): = { } def program(): = { }
  • 21. Properties of pure functions ● Total ● Deterministic ● Free of side effects
  • 23. What is IO[E, A] ? IO is an immutable data structure that describes an effectful program that may: ● fail with an E ● run forever ● produce a single A
  • 24. What is IO[E, A] ? parseInt("hello") //fails with NumberFormatExceptionIO.syncException(parseInt(str))
  • 26. What is IO[E, A] ? println("Hello!")IO.sync(println("Hello!")
  • 27. What is IO[E, A] ? throw new Exception("error")IO.fail(new Exception("error"))
  • 28. What is IO[E, A] ? while(true) {}IO.never
  • 29. IO[E, A] structure trait IO[E, A] { self => def map[B](f: A => B): IO[E, B] def flatMap[E, B](f0: A => IO[E, B]): IO[E, B] ... } object IO { def fail[E](error: E): IO[E, Nothing] = ??? def now[A](a: A): IO[Nothing, A] = ??? ... } IO[E, A]
  • 30. IO Effects IO describes the following effects: ● Pure Values val number: Int= 1 val number: IO[Nothing, Int] = IO.now(1)
  • 31. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect println("hello") val putStrLn: IO[Nothing, Unit] = IO.sync(println("hello"))
  • 32. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect parseInt("hello") val toInt: IO[Throwable, Int] = IO.syncThrowable(parseInt("hello"))
  • 33. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect parseInt("hello") val toInt: IO[Exception, Int] = IO.syncException(parseInt("hello"))
  • 34. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect parseInt("hello") val toInt: IO[String, Int] = IO.syncCatch(parseInt("hello")){ case e: NumberFormatException => "oh no!" }
  • 35. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect ● Asynchronous Effects Future(4) IO.async[Nothing, Int](_(Completed(4)))
  • 36. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect ● Asynchronous Effects ● Concurrent Effects val hello = new Thread(new Runnable { def run() { while (true) { println("hello world") } } }) for { f <- IO.sync(println("hello world")).fork _ <- f.join } yield ()
  • 37. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect ● Asynchronous Effects ● Concurrent Effects val hello = new Thread(new Runnable { def run() { while (true) { println("hello world") } } }) for { f <- IO.sync(println("hello world")).forever.fork _ <- f.interrupt } yield ()
  • 38. IO Effects IO describes the following effects: ● Pure Values ● Synchronous Effect ● Asynchronous Effects ● Concurrent Effects ● Resource Effects val f: File = openFile() try { compute(f) } finally { closeFile(f) //Unit } IO.bracket[Error, File, Unit](openFile()) (f => closeFile(f))(f => compute(f))
  • 39. Usage of IO In ZIO, every type has specific features to solve different problems. Each type is wrapped inside an IO. Promise[E, A] Ref[A] Queue[A] IO[E, A]
  • 40. RTS: IO runtime system IO is interpreted by the IO runtime system into effectful interactions with the external world. ● unsafeRun ● In your application’s main function (App provides this functionality automatically). def main(args: Array[String]): Unit = println("Hello") def main(args: Array[String]): Unit = unsafeRun(IO.sync(println("Hello")))
  • 41. Ref Ref is the equivalent of `var` Ref has an AtomicReference to apply the atomic operations on it.
  • 42. Ref Ref[A] object Ref { def apply[A](a: A): IO[Nothing, Ref[A]] = ??? } trait Ref[A] { def get: IO[Nothing, A] def set(a: A): IO[Nothing, Unit] def update(f: A => A): IO[Nothing, A] def modify[B](f: A => (B, A)): IO[Nothing, B] }
  • 43. Example for { counter <- Ref(0) v <- counter.update(_ + 1) } yield v for { counter <- Ref(0) v <- counter.modify { prev => val newValue = prev + 1 (s"previous value: $prev, next value is: $newValue", newValue) } _ <- IO.sync(println(v)) } yield ()
  • 44. Promise A Promise is an asynchronous variable that can be set only once.
  • 45. Promise A Promise is an asynchronous variable that can be set only once. `error`: fails the promise with the specified error, which will be propagated to all fibers waiting on the value of promise.
  • 46. Promise A Promise is an asynchronous variable that can be set only once. `complete`: completes the promise with the specified value.
  • 47. Promise By default the state of Promise is Pending, once it fails or completes the state changes to Done. `done`: completes the promise with the specified result. A Promise is an asynchronous variable that can be set only once.
  • 48. Promise trait Promise[E, A] { def get: IO[E, A] def complete(a: A): IO[Nothing, Boolean] def error(e: E): IO[Nothing, Boolean] def interrupt(t: Throwable): IO[Nothing, Boolean] def done(r: ExitResult[E, A]): IO[Nothing, Boolean] } Promise[E, A] object Promise { def make[E, A]: IO[Nothing, Promise[E, A]] = ??? }
  • 49. Promise: Example Get an alert for your friends’s birthday, as follow up reminder to offer the appropriate “happy birthday” greeting. 🎂
  • 50. Promise: Example (for { p <- Promise.make[Nothing, String] _ <- p.complete(s"Your reminder for ${friend.name} birthday") .delay(minus(LocalDate.now, friend.birthday)) .fork msg <- p.get } yield sendAlert(msg)).fork 20.12.2018
  • 51. QUEUE
  • 52. Queue Queue is an asynchronous queue which allows to add and remove elements in First In First Out manner.
  • 54. trait Queue[A] { def take: IO[Nothing, A] def takeAll: IO[Nothing, List[A]] def takeUpTo(max: Int): IO[Nothing, List[A]] def offer(a: A): IO[Nothing, Boolean] def offerAll(as: Iterable[A]): IO[Nothing, Boolean] } object Queue { def bounded[A](capacity: Int): IO[Nothing, Queue[A]] def unbounded[A]: IO[Nothing, Queue[A]] def sliding[A](capacity: Int): IO[Nothing, Queue[A]] def dropping[A](capacity: Int): IO[Nothing, Queue[A]] } Queue[A] Queue
  • 55. Takers take Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork
  • 56. Takers take take Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork v2 <- queue.take.fork
  • 57. Takers take take Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork v2 <- queue.take.fork _ <- queue.offer("hello").fork “hello” Producers
  • 58. Takers take take Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork v2 <- queue.take.fork _ <- queue.offer("hello").fork _ <- queue.offer("bye").fork Producers “hello” “bye”
  • 59. Takers take take Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork v2 <- queue.take.fork _ <- queue.offer("hello").fork _ <- queue.offer("bye").fork Producers “bye” “hello”
  • 60. Takers Consumers for { queue <- Queue.unbounded[String] v1 <- queue.take.fork v2 <- queue.take.fork _ <- queue.offer("hello").fork _ <- queue.offer("bye").fork } yield () Producers “hello” “bye”
  • 61. Back pressure A bounded Queue with capacity = 3 for { queue <- Queue.bounded[String](3)
  • 62. Back pressure “b” “c” “a” “d” “b” “c” Producers for { queue <- Queue.bounded[String](3) _ <- queue.offer("a").fork _ <- queue.offer("b").fork _ <- queue.offer("c").fork _ <- queue.offer("d").fork
  • 63. Back pressure “c” “b” “a” offer(“d”) Producers for { queue <- Queue.bounded[String](3) _ <- queue.offer("a").fork _ <- queue.offer("b").fork _ <- queue.offer("c").fork _ <- queue.offer("d").fork
  • 64. Back pressure take offer(“d”) ConsumersProducers for { queue <- Queue.bounded[String](3) _ <- queue.offer("a").fork _ <- queue.offer("b").fork _ <- queue.offer("c").fork _ <- queue.offer("d").fork v1 <- queue.take.fork “c” “b” “a”
  • 65. Back pressure “c” “b” offer(“d”) Consumers “a” Producers for { queue <- Queue.bounded[String](3) _ <- queue.offer("a").fork _ <- queue.offer("b").fork _ <- queue.offer("c").fork _ <- queue.offer("d").fork v1 <- queue.take.fork
  • 66. Back pressure “d” “c” “b” ConsumersProducers for { queue <- Queue.bounded[String](3) _ <- queue.offer("a").fork _ <- queue.offer("b").fork _ <- queue.offer("c").fork _ <- queue.offer("d").fork v1 <- queue.take.fork } yield ()
  • 67. Sliding for { queue <- Queue.sliding[String](3) _ <- queue.offer("A") //(1) } yield ()
  • 68. Sliding for { queue <- Queue.sliding[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) } yield ()
  • 69. Sliding for { queue <- Queue.sliding[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("C") //(3) } yield ()
  • 70. Sliding for { queue <- Queue.sliding[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("C") //(3) _ <- queue.offer("D") //(4) } yield ()
  • 71. Sliding for { queue <- Queue.sliding[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("C") //(3) _ <- queue.offer("D") //(4) } yield ()
  • 72. Dropping for { queue <- Queue.dropping[String](3) _ <- queue.offer("A") //(1) } yield ()
  • 73. Dropping for { queue <- Queue.dropping[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) } yield ()
  • 74. Dropping for { queue <- Queue.dropping[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("C") //(3) } yield ()
  • 75. Dropping for { queue <- Queue.dropping[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("C") //(3) _ <- queue.offer("D") //(4) } yield ()
  • 76. Dropping for { queue <- Queue.dropping[String](3) _ <- queue.offer("A") //(1) _ <- queue.offer("B") //(2) _ <- queue.offer("D") //(4) } yield ()
  • 77. Shutdown for { queue <- Queue.unbounded[String] _ <- queue.offer("A").forever.fork _ <- queue.take.forever.fork } yield ()
  • 78. Shutdown for { queue <- Queue.unbounded[String] _ <- queue.offer("A").forever.fork _ <- queue.take.forever.fork _ <- queue.shutdown } yield ()
  • 79. Shutdown for { queue <- Queue.unbounded[String] _ <- queue.offer("A").forever.fork _ <- queue.take.forever.fork _ <- queue.shutdown } yield ()