Stream
- Companion
- class
trait StreamLowPriority
class Object
trait Matchable
class Any
Type members
Classlikes
final class NestedStreamOps[F <: ([_$147] =>> Any), O](outer: Stream[F, Stream[F, O]]) extends AnyVal
Provides syntax for streams of streams.
final class StepLeg[F <: ([_$176] =>> Any), O](val head: Chunk[O], val scopeId: Unique, val next: Pull[F, O, Unit])
When merging multiple streams, this represents step of one leg.
It is common to
of stream scope independently of the main scope of the stream.
uncons
, however unlike uncons
, it keeps trackof stream scope independently of the main scope of the stream.
This assures, that after each next
when interpreting.
stepLeg
each Stream leg
keeps its scopewhen interpreting.
Usual scenarios is to first invoke
available in
stream.pull.stepLeg
and then consume whatever isavailable in
leg.head
. If the next step is required leg.stepLeg
will yield next Leg
.Once the stream will stop to be interleaved (merged), then
invocation.
stream
allows to return to normal streaminvocation.
Value members
Methods
Creates a pure stream that emits the supplied values. To convert to an effectful stream, use
covary
. def attemptEval[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), O](fo: F[O]): Stream[F, Either[Throwable, O]]
Creates a single element stream that gets its value by evaluating the supplied effect. If the effect fails, a
is emitted. Otherwise, a
Left
is emitted. Otherwise, a
Right
is emitted.Use eval instead if a failure while evaluating the effect should fail the stream.
- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.attemptEval(SyncIO(10)).compile.toVector.unsafeRunSync()
res0: Vector[Either[Throwable,Int] ] = Vector(Right(10))
scala> Stream.attemptEval(SyncIO(throw new RuntimeException)).compile.toVector.unsafeRunSync()
res1: Vector[Either[Throwable,Nothing] ] = Vector(Left(java.lang.RuntimeException))
}}}
def awakeDelay[F <: ([_$72] =>> Any)](period: FiniteDuration)(t: Temporal[F]): Stream[F, FiniteDuration]
Light weight alternative to
awakeEvery
that sleeps for duration d
before each pulled element. def awakeEvery[F <: ([_$74] =>> Any)](period: FiniteDuration)(evidence$46: Temporal[F]): Stream[F, FiniteDuration]
Discrete stream that every
since the start time of stream consumption.
d
emits elapsed durationsince the start time of stream consumption.
Missed periods are dampened to a single tick.
For example:
return (approximately)
between emitted values.
awakeEvery[IO](5 seconds)
willreturn (approximately)
5s, 10s, 15s
, and will lie dormantbetween emitted values.
- Value Params
- period
-
duration between emits of the resulting stream
def awakeEvery[F <: ([_$75] =>> Any)](period: FiniteDuration, dampen: Boolean)(t: Temporal[F]): Stream[F, FiniteDuration]
Discrete stream that every
since the start time of stream consumption.
d
emits elapsed durationsince the start time of stream consumption.
For example:
return (approximately)
between emitted values.
awakeEvery[IO](5 seconds)
willreturn (approximately)
5s, 10s, 15s
, and will lie dormantbetween emitted values.
- Value Params
- dampen
-
whether missed periods result in 1 emitted tick or 1 per missed period, see fixedRate for more info
- period
-
duration between emits of the resulting stream
def bracket[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: F[R])(release: R => F[Unit]): Stream[F, R]
Creates a stream that emits a resource allocated by an effect, ensuring the resource is
eventually released regardless of how the stream is used.
eventually released regardless of how the stream is used.
A typical use case for bracket is working with files or network sockets. The resource effect
opens a file and returns a reference to it. One can then flatMap on the returned Stream to access
the file, e.g to read bytes and transform them in to some stream of elements
(e.g., bytes, strings, lines, etc.).
The
or errors.
opens a file and returns a reference to it. One can then flatMap on the returned Stream to access
the file, e.g to read bytes and transform them in to some stream of elements
(e.g., bytes, strings, lines, etc.).
The
release
action then closes the file once the result Stream terminates, even in case of interruptionor errors.
- Value Params
- acquire
-
resource to acquire at start of stream
- release
-
function which returns an effect that releases the resource
def bracketWeak[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: F[R])(release: R => F[Unit]): Stream[F, R]
Like bracket but no scope is introduced, causing resource finalization to
occur at the end of the current scope at the time of acquisition.
occur at the end of the current scope at the time of acquisition.
def bracketCase[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: F[R])(release: (R, ExitCase) => F[Unit]): Stream[F, R]
Like bracket but the release action is passed an
ExitCase[Throwable]
.ExitCase.Canceled
is passed to the release action in the event of either stream interruption oroverall compiled effect cancelation.
def bracketCaseWeak[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: F[R])(release: (R, ExitCase) => F[Unit]): Stream[F, R]
Like bracketCase but no scope is introduced, causing resource finalization to
occur at the end of the current scope at the time of acquisition.
occur at the end of the current scope at the time of acquisition.
def bracketFull[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: Poll[F] => F[R])(release: (R, ExitCase) => F[Unit])(F: MonadCancel[F, ]): Stream[F, R]
Like bracketCase but the acquire action may be canceled.
def bracketFullWeak[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), R](acquire: Poll[F] => F[R])(release: (R, ExitCase) => F[Unit])(F: MonadCancel[F, ]): Stream[F, R]
Like bracketFull but no scope is introduced, causing resource finalization to
occur at the end of the current scope at the time of acquisition.
occur at the end of the current scope at the time of acquisition.
Creates a pure stream that emits the elements of the supplied chunk.
- Example
- {{{
scala> Stream.chunk(Chunk(1,2,3)).toList
res0: List[Int] = List(1, 2, 3)
}}}
Creates an infinite pure stream that always returns the supplied value.
Elements are emitted in finite chunks with
chunkSize
number of elements.- Example
- {{{
scala> Stream.constant(0).take(5).toList
res0: List[Int] = List(0, 0, 0, 0, 0)
}}}
A continuous stream of the elapsed time, computed using
Note that the actual granularity of these elapsed times depends on the OS, for instance
the OS may only update the current time every ten milliseconds or so.
System.nanoTime
.Note that the actual granularity of these elapsed times depends on the OS, for instance
the OS may only update the current time every ten milliseconds or so.
Creates a singleton pure stream that emits the supplied value.
- Example
- {{{
scala> Stream.emit(0).toList
res0: List[Int] = List(0)
}}}
Creates a pure stream that emits the supplied values.
- Example
- {{{
scala> Stream.emits(List(1, 2, 3)).toList
res0: List[Int] = List(1, 2, 3)
}}}
Creates a single element stream that gets its value by evaluating the supplied effect. If the effect fails,
the returned stream fails.
the returned stream fails.
Use attemptEval instead if a failure while evaluating the effect should be emitted as a value.
- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.eval(SyncIO(10)).compile.toVector.unsafeRunSync()
res0: Vector[Int] = Vector(10)
scala> Stream.eval(SyncIO(throw new RuntimeException)).covaryOutput[Int] .compile.toVector.attempt.unsafeRunSync()
res1: Either[Throwable,Vector[Int] ] = Left(java.lang.RuntimeException)
}}}
@deprecated("Use exec if passing an F[Unit] or eval(fa).drain if passing an F[A]", "2.5.0")
Creates a stream that evaluates the supplied
As a result, the returned stream emits no elements and hence has output type
fa
for its effect, discarding the output value.As a result, the returned stream emits no elements and hence has output type
INothing
.Alias for
eval(fa).drain
. def evals[F <: ([_$85] =>> Any), S <: ([_$86] =>> Any), O](fo: F[S[O]])(evidence$47: Foldable[S]): Stream[F, O]
Like
eval
, but lifts a foldable structure. def every[F <: ([_$88] =>> Any)](d: FiniteDuration)(clock: Clock[F], F: Functor[F]): Stream[F, Boolean]
A continuous stream which is true after
and false otherwise.
If you'd like a 'discrete' stream that will actually block until
use
d, 2d, 3d...
elapsed duration,and false otherwise.
If you'd like a 'discrete' stream that will actually block until
d
has elapsed,use
awakeEvery
instead.As a result, the returned stream emits no elements and hence has output type
INothing
.- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.exec(SyncIO(println("Ran"))).covaryOutput[Int] .compile.toVector.unsafeRunSync()
res0: Vector[Int] = Vector()
}}}
Light weight alternative to fixedRate that sleeps for duration
d
before each pulled element.Behavior differs from
is pulled whereas
This difference can roughly be thought of as the difference between
fixedRate
because the sleep between elements occurs after the next elementis pulled whereas
fixedRate
accounts for the time it takes to process the emitted unit.This difference can roughly be thought of as the difference between
scheduleWithFixedDelay
andscheduleAtFixedRate
in java.util.concurrent.Scheduler
.Alias for
sleep(period).repeat
.Discrete stream that emits a unit every
d
, with missed period ticks dampened.See fixedDelay for an alternative that sleeps
d
between elements.- Value Params
- period
-
duration between emits of the resulting stream
def fixedRate[F <: ([_$93] =>> Any)](period: FiniteDuration, dampen: Boolean)(F: Temporal[F]): Stream[F, Unit]
Discrete stream that emits a unit every
d
.See fixedDelay for an alternative that sleeps
d
between elements.This operation differs in that the time between ticks should roughly be equal to the specified period, regardless
of how much time it takes to process that tick downstream. For example, with a 1 second period and a task that takes 100ms,
the task would run at timestamps, 1s, 2s, 3s, etc. when using
1s, 2.1s, 3.2s, etc. when using
of how much time it takes to process that tick downstream. For example, with a 1 second period and a task that takes 100ms,
the task would run at timestamps, 1s, 2s, 3s, etc. when using
fixedRate >> task
whereas it would run at timestamps1s, 2.1s, 3.2s, etc. when using
fixedDelay >> task
.In the case where task processing takes longer than a single period, 1 or more ticks are immediately emitted to "catch-up".
The
The
dampen
parameter controls whether a single tick is emitted or whether one per missed period is emitted.- Value Params
- dampen
-
true if a single unit should be emitted when multiple periods have passed since last execution, false if a unit for each period should be emitted
- period
-
period between emits of the resulting stream
Lifts an Either[Throwable, A]
to an effectful Stream.
- Example
- {{{
scala> import cats.effect.SyncIO, scala.util.Try
scala> Stream.fromEitherSyncIO.compile.toList.unsafeRunSync()
res0: List[Int] = List(42)
scala> Try(Stream.fromEither[SyncIO] (Left(new RuntimeException)).compile.toList.unsafeRunSync())
res1: Try[List[Nothing] ] = Failure(java.lang.RuntimeException)
}}}
def fromQueueUnterminated[F <: ([_$105] =>> Any), A](queue: Queue[F, A], limit: Int)(evidence$49: Functor[F]): Stream[F, A]
Returns a stream of elements from the supplied queue.
All elements that are available, up to the specified limit,
are dequeued and emitted as a single chunk.
are dequeued and emitted as a single chunk.
def fromQueueUnterminatedChunk[F <: ([_$107] =>> Any), A](queue: Queue[F, Chunk[A]], limit: Int)(evidence$50: Functor[F]): Stream[F, A]
Returns a stream of elements from the supplied queue.
All elements that are available, up to the specified limit,
are dequeued and emitted as a single chunk.
are dequeued and emitted as a single chunk.
def fromQueueNoneTerminated[F <: ([_$111] =>> Any), A](queue: Queue[F, Option[A]], limit: Int)(evidence$51: Functor[F]): Stream[F, A]
Returns a stream of elements from the supplied queue.
The stream terminates upon dequeuing a
None
.All elements that are available, up to the specified limit,
are dequeued and emitted as a single chunk.
are dequeued and emitted as a single chunk.
def fromQueueNoneTerminatedChunk[F <: ([_$115] =>> Any), A](queue: Queue[F, Option[Chunk[A]]], limit: Int): Stream[F, A]
Returns a stream of elements from the supplied queue.
The stream terminates upon dequeuing a
None
.All elements that are available, up to the specified limit,
are dequeued and emitted as a single chunk.
are dequeued and emitted as a single chunk.
def foldable[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), G <: ([_$117] =>> Any), O](os: G[O])(evidence$52: Foldable[G]): Stream[F, O]
Like
emits
, but works for any G that has a Foldable
instance.Lifts an effect that generates a stream in to a stream. Alias for
eval(f).flatMap(_)
.- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.force(SyncIO(Stream(1,2,3).covary[SyncIO] )).compile.toVector.unsafeRunSync()
res0: Vector[Int] = Vector(1, 2, 3)
}}}
An infinite
to a start value.
by
Stream
that repeatedly applies a given functionto a start value.
start
is the first value emitted, followedby
f(start)
, then f(f(start))
, and so on.- Example
- {{{
scala> Stream.iterate(0)(_ + 1).take(10).toList
res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
}}}
Like iterate, but takes an effectful function for producing
the next state.
the next state.
start
is the first value emitted.- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.iterateEval(0)(i => SyncIO(i + 1)).take(10).compile.toVector.unsafeRunSync()
res0: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
}}}
def raiseError[F <: ([_$123] =>> Any)](e: Throwable)(evidence$53: RaiseThrowable[F]): Stream[F, INothing]
Creates a stream that, when run, fails with the supplied exception.
The
F
type must be explicitly provided (e.g., via raiseError[IO]
or raiseError[Fallible]
).- Example
- {{{
scala> import cats.effect.SyncIO
scala> Stream.raiseError[Fallible] (new RuntimeException).toList
res0: Either[Throwable,List[INothing] ] = Left(java.lang.RuntimeException)
scala> Stream.raiseError[SyncIO] (new RuntimeException).covaryOutput[Int] .compile.drain.attempt.unsafeRunSync()
res0: Either[Throwable,Unit] = Left(java.lang.RuntimeException)
}}}
Creates a random stream of integers using the supplied seed.
Returns a pure stream, as the pseudo random number generator is
deterministic based on the supplied seed.
Returns a pure stream, as the pseudo random number generator is
deterministic based on the supplied seed.
def range[F >: ([x] =>> Pure[x]) <: ([x] =>> Any)](start: Int, stopExclusive: Int, by: Int): Stream[F, Int]
Lazily produce the range
the sequence in one chunk, instead of lazily, use
[start, stopExclusive)
. If you want to producethe sequence in one chunk, instead of lazily, use
emits(start until stopExclusive)
.- Example
- {{{
scala> Stream.range(10, 20, 2).toList
res0: List[Int] = List(10, 12, 14, 16, 18)
}}}
def ranges[F >: ([x] =>> Pure[x]) <: ([x] =>> Any)](start: Int, stopExclusive: Int, size: Int): Stream[F, (Int, Int)]
Lazily produce a sequence of nonoverlapping ranges, where each range
contains
Example:
contains
size
integers, assuming the upper bound is exclusive.Example:
ranges(0, 1000, 10)
results in the pairs(0, 10), (10, 20), (20, 30) ... (990, 1000)
Note: The last emitted range may be truncated at
instance,
stopExclusive
. Forinstance,
ranges(0,5,4)
results in (0,4), (4,5)
.- Throws
- IllegalArgumentException
- IllegalArgumentException
- Example
- {{{
scala> Stream.ranges(0, 20, 5).toList
res0: List[(Int,Int)] = List((0,5), (5,10), (10,15), (15,20))
}}}
def retry[F <: ([_$129] =>> Any), O](fo: F[O], delay: FiniteDuration, nextDelay: FiniteDuration => FiniteDuration, maxAttempts: Int, retriable: Throwable => Boolean)(evidence$54: Temporal[F], evidence$55: RaiseThrowable[F]): Stream[F, O]
Retries
result of
fo
on failure, returning a singleton stream with theresult of
fo
as soon as it succeeds.- Value Params
- delay
-
Duration of delay before the first retry
- maxAttempts
-
Number of attempts before failing with the
latest error, iffo
never succeeds - nextDelay
-
Applied to the previous delay to compute the
next, e.g. to implement exponential backoff - retriable
-
Function to determine whether a failure is
retriable or not, defaults to retry everyNonFatal
. A failed stream is immediately
returned when a non-retriable failure is
encountered
Alias for
performant version of
sleep(d).drain
. Often used in conjunction with ++
(i.e., sleep_(..) ++ s
) as a moreperformant version of
sleep(..) >> s
. def supervise[F <: ([_$135] =>> Any), A](fa: F[A])(F: Concurrent[F]): Stream[F, Fiber[F, Throwable, A]]
Starts the supplied task and cancels it as finalization of the returned stream.
Returns a stream that evaluates the supplied by-name each time the stream is used,
allowing use of a mutable value in stream computations.
allowing use of a mutable value in stream computations.
Note: it's generally easier to reason about such computations using effectful
values. That is, allocate the mutable value in an effect and then use
values. That is, allocate the mutable value in an effect and then use
Stream.eval(fa).flatMap { a => ??? }
.- Example
- {{{
scala> Stream.suspend {
| val digest = java.security.MessageDigest.getInstance("SHA-256")
| val bytes: Stream[Pure,Byte] = ???
| bytes.chunks.fold(digest) { (d,c) => d.update(c.toBytes.values); d }
| }
}}}
def unfold[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), S, O](s: S)(f: S => Option[(O, S)]): Stream[F, O]
Creates a stream by successively applying
each output
f
until a None
is returned, emittingeach output
O
and using each output S
as input to the next invocation of f
.- Example
- {{{
scala> Stream.unfold(0)(i => if (i < 5) Some(i -> (i+1)) else None).toList
res0: List[Int] = List(0, 1, 2, 3, 4)
}}}
def unfoldChunk[F >: ([x] =>> Pure[x]) <: ([x] =>> Any), S, O](s: S)(f: S => Option[(Chunk[O], S)]): Stream[F, O]
Like unfold but each invocation of
f
provides a chunk of output.- Example
- {{{
scala> Stream.unfoldChunk(0)(i => if (i < 5) Some(Chunk.seq(List.fill(i)(i)) -> (i+1)) else None).toList
res0: List[Int] = List(1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
}}}
def unfoldChunkEval[F <: ([_$139] =>> Any), S, O](s: S)(f: S => F[Option[(Chunk[O], S)]]): Stream[F, O]
Like unfoldChunk, but takes an effectful function.
Creates a stream by successively applying
each output
if it is Some, or terminating on None
f
to a S
, emittingeach output
O
and using each output S
as input to the next invocation of f
if it is Some, or terminating on None
- Example
- {{{
scala> Stream.unfoldLoop(0)(i => (i, if (i < 5) Some(i+1) else None)).toList
res0: List[Int] = List(0, 1, 2, 3, 4, 5)
}}}
Implicits
Implicits
implicit def monadErrorInstance[F <: ([_$182] =>> Any)](ev: ApplicativeError[F, Throwable]): MonadError[[_$183] =>> Stream[F, _$183], Throwable]
MonadError
instance for Stream
.- Example
- {{{
scala> import cats.syntax.all._
scala> Stream(1, -2, 3).fproduct(_.abs).toList
res0: List[(Int, Int)] = List((1,1), (-2,2), (3,3))
}}}
Align
instance for Stream
.* @example
{{{
scala> import cats.syntax.all._
scala> Stream(1,2,3).align(Stream("A","B","C","D","E")).toList
res0: List[cats.data.Ior[Int,String] ] = List(Both(1,A), Both(2,B), Both(3,C), Right(D), Right(E))
}}}
implicit def functorFilterInstance[F <: ([_$199] =>> Any)]: FunctorFilter[[_$200] =>> Stream[F, _$200]]
FunctorFilter
instance for Stream
.- Example
- {{{
scala> import cats.syntax.all., scala.util.
scala> Stream("1", "2", "NaN").mapFilter(s => Try(s.toInt).toOption).toList
res0: List[Int] = List(1, 2)
}}}
FunctionK
instance for F ~> Stream[F, *]
- Example
- {{{
scala> import cats.Id
scala> Stream.functionKInstanceId.compile.toList
res0: cats.Id[List[Int] ] = List(42)
}}}