fs2
Pure Streams
Section titled “Pure Streams”- create finite streams:
apply,empty,emit,emits,range - create infinite:
iterate,unfold,constant Stream[F, A]#chunks => Stream[F, Chunk[A]]convert a stream of types to chunked streamStream[F, Chunk[A]].flatMap(c => Stream.chunk(c)) => Stream[F, A]revert the chunked version to stream of type- building a stream
emit(_: A),emits(_: Seq[A])produceStream[Nothing, A]eval(_: F[A])=>Stream[F, A]- infinite stream:
Stream.constant(42),Stream.awakeEvery[IO].(1.second),Stream.iterate(1.0)(_ * 2)
- combinators:
map,filter,flatMap++: appends second stream to the first streamdrain: discard all elementsfind(O => Boolean): emits first element that matcheshead,take(n),interruptAfter(10.minutes),interruptWhen(<condition>)zip,st1.zipWith(st2)(fn),zipLeft/Right: like zip, but keep only left/right streamcompile: a projection of a stream that allows it to be converted to other types; e.g.stream.compile.toList
- retries:
Stream.retry(action, delay = 1.second, nextDelay = _ * 2, maxAttempts = 3)
Effectful Streams
Section titled “Effectful Streams”- create:
eval,covary,iterateEval,unfoldEvalcovarycan convert not only pure streams, but any effect into another effectexec, likeevalbut doesn’t produce any elementfromIteratoris effectful because anIteratormaintains a stateStream.unfoldcan seeminly produce a pure stream, but it is unsafe because the functionIterator#nextmutates hidden state
- must be compiled
- can be compiled to a value
.compile.toListor just for the effect.compile.drain
- can be compiled to a value
- combinators:
evalMap,evalTap,evalFilter,++- transformation:
map(A => B),flatMap(A => Stream[F, B]),evalMap()
- transformation:
- Error handling:
raiseError,handleErrorWith - Resource handling:
bracket,resource,fromAutoCloseable
val file: Stream[IO, BufferedReader] = Stream.bracket { IO { new BufferedReader(new FileReader(new File("./build.sbt"))) }}(f => IO(f.close())
file.flatMap { reader => Stream .eval(IO(Option(reader.readLine()))) .repeat .unNoneTerminate}.map(_.length) // returns an integer for each line read from the fileTimer combinators
Section titled “Timer combinators”timeout(1.second): throws an exception if the stream isn’t consumed in 1 secondinterruptAfter(1.second): stops stream from emitting any more data after 1 seconddelayBy(2.second): delays emitting the first element by 2 secondsmetered: delays every emit. Delay is measured from previous delay, i.e. it’s not affected by processing time taken by actual emitdebounce(1.second): sampling, emit only at intervals
Resource Management
Section titled “Resource Management”val acq = IO.blocking(new BufferReader(new FileReader("input.csv")))val rel = (r: BufferReader) => IO.blocking(r.close())val res = Resource.make(acq)(rel)
val read = (r: BufferReader) => Stream.repeatEval(IO.blocking(r.readLine())).takeWhile(_ != null)
Stream.bracket(acq)(rel).flatMap(read)Stream.resource(res).flatMap(read)Stream.fromAutoCloseable(acq).flatMap(read)Error Handling
Section titled “Error Handling”StreamimplementsMonadErrorraiseError[F]causes failure and rest of the stream to be ignored. Any side-effects from earlier are evaluatedhandleErrorWithcauses stream to stop and rest of the elements discarded.attemptcatches error and converts to aLeft, any previous elements are returned asRight
Pipeline
Section titled “Pipeline”- internal buffer implementation for performance, fast concat, fast indexing, avoid copying, list-like interface
- constructors:
apply,singleton,array,empty - combinators:
map,flatMap,filter,take - methods:
size: total number of elements in the chunkcopyToArray: replace existing elements of an array from chunkcompact: physically combine all contained chunks into a single chunk
- represent process for stream transformations, including stateful
- has 3 type parameters
Pull[F, A, R],F: effect,Aelement type,Ris result Pullis a monad over its result type- constructors:
output1: accepts a single element, withUnitas result typepure[A]: emits nothing,Ais result typeoutput: accepts aChunk,Unitis result typedone: indicates end of dataStream.pull: converts aStreamtoToPull(an intermediate type before finally converting toPull)
- methods:
stream: convertsPullto aStreamscanChunksOpt: likefoldbut atChunklevel and can returnNoneif remainder of theStreamneeds to be discarded
- converting streams to
ToPullusings.pull;ToPullis ToPullmethods:echo: copies elements of a stream to a newPull, returnsUnittake(5): copies 5 elements of a stream to a newPulland returnsOption[Stream[F, A]], which is a stream of rest of the elementsdrop(5): same astake(5)except it drops the elementsuncons() : Option[(Chunk[A], Stream[F, A])]: returns the first chunk from the stream and rest of the stream- useful in building
Pipe(Streamtransformations)
- useful in building
- stream transformation function: of type
Stream[F, A] => Stream[F, B] - typical recipe:
- create as a function that takes a stream
- create a pull
- use
unconsto get the first chunk and remainder (a stream) - process chunk
- recursively process the remainder
Parallel Processing
Section titled “Parallel Processing”st1.merge(st2): runs both streams in parallel and merges results as they become available from either streams- final stream fails when either stream fails
mergeHaltLmergeHaltRmergeHaltBothvariations stop the stream when either left, right or both streams are exhausted
st1.concurrently(st2)is similar tomerge, exceptst1is treated as dominant or primary, andst2is secondary. values fromst2are obtained only if items fromst1are unavailable- use case: primary stream could do the processing and secondary stream could report progress
- use case: implement independent consumer and producer using cats
Queue
Stream(st1, st2, ...).parJoinUnboundedis generalized version ofmerge.parJoin(n)runs max n streams at a time, degree of parallelism
parEvalMap: likeevalMap- use case: a queue with multiple consumers and producers using
cats.effect.Queue
def producer(id: Int, queue: Queue[IO, Int]): Stream[IO, Nothing] = Stream.repeatEval(queue.offer(id)).draindef consumer(id: Int, queue: Queue[IO, Int]): Stream[IO, Nothing] = Stream.repeatEval(queue.take(id)).printlns
Stream.eval(Queue.unbounded[IO, Int]).flatMap { queue => val ps = Stream.range(0, 4).map(id => producer(id, queue)) // 4 producers val cs = Stream.range(0, 6).map(id => consumer(id, queue)) // 6 consumers (ps ++ cs).parJoinUnbounded // run all concurrently}.interruptAfter(5.second).compile.drainparZip: unlikezipis non-deterministic, i.e. it’ll pull from whichever stream is ready and then wait for the otherparEvalMap: likeevalMapbut runs in parallel, still keeps the order of individual elements processedStream.fixedRate: produces a unit value at every fixed interval; generally used withzipRightto throttle another stream- can implement
meteredwithfixRateandzipRight
- can implement
Stream.fixedDelay: likefixedRateexcept the delay between two emits is constant; similar tospacedawakeDelayandawakeEverylikefixedDelayandfixedRateexcept the emit the time-interval in nano-second
Communication
Section titled “Communication”- communicate between concurrent streams
SignallingRef
Section titled “SignallingRef”- signal from one process to another
.set: set a value.descrete: Stream[IO, T]: returns a value when a signal is receivedinterruptWhen(signal): whensignalisBoolean; like interrupt, except the worker stream checks for a signal after every emit instead of terminating abruptly
- example:
type Temperature = Doubleval program = Stream.eval(SignallingRef[IO, Temperature](20.0)).flatMap { alarm => val sensor = Stream.repeatEval(IO(Random.between(-40, 40))).evalMap(t => (if t >= 25) alarm.set(t) else IO.unit).metered(300.millis).drain val cooler = alarm.descrete.evalMap(t => IO.println(f"$t%.1f is too high")).drain cooler.merge(sensor)}program.interruptAfter(3.seconds).compile.drainChannel
Section titled “Channel”- for more than 1 value, more than 1 producer
Channel.unboundedfor unlimited capacity andChannel.bounded(n)to holdnitems.sendfor producers, send values to the channel.streamfor consumers,
- example:
type Temperature = Doubleval program = Stream.eval(Channel[IO, Temperature](20.0)).flatMap { alarm => val sensor = Stream.repeatEval(IO(Random.between(-40, 40))).evalMap(t => (if t >= 25) alarm.send(t) else IO.unit).metered(300.millis).drain val cooler = alarm.stream.evalMap(t => IO.println(f"$t%.1f is too high")).drain cooler.merge(sensor)}program.interruptAfter(3.seconds).compile.drain- for more than 1 value, 1+ producers, 1+ independent consumers
.publishfor producers.subscribe(n)for consumers, buffer to hold unread items, each consumer reads all items- creates back-pressure to stop producer instead of overrunning slow consumers
- 1+ values, 1+ producers, 1+ shared consumers
Queue.unboundedfor unlimited capacity andQueue.bounded(n)forncapacity- Producers:
.offer - Consumers:
Stream.fromQueueUnterminated(queue)for infinite queuesStream.from QueueNoneTerminated(queue)each item is available until a it’s terminated. Producers must offer each value asSomeorNone
- Producers: