Source

ox.channels.Source
See theSource companion object
trait Source[+T] extends SourceOps[T], SourceDrainOps[T], SourceIOOps[T], SourceTextOps[T]

A channel source, which can be used to receive values from the channel. See Channel for more details.

Attributes

Companion
object
Graph
Supertypes
trait SourceTextOps[T]
trait SourceIOOps[T]
trait SourceDrainOps[T]
trait SourceOps[T]
class Object
trait Matchable
class Any
Show all
Known subtypes
class Channel[T]

Members list

Type members

Classlikes

case class Receive extends SelectClause[T]

The clause passed to select, created using receiveClause or receiveOrDoneClause.

The clause passed to select, created using receiveClause or receiveOrDoneClause.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SelectClause[T]
class Object
trait Matchable
class Any
Show all
case class Received extends SelectResult[T]

Holds the result of a receiveClause that was selected during a call to select.

Holds the result of a receiveClause that was selected during a call to select.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
trait SelectResult[T]
class Object
trait Matchable
class Any
Show all

Value members

Concrete methods

def isClosedForReceive: Boolean

Attributes

Returns

true if no more values can be received from this channel; Source.receive will throw ChannelClosedException. When closed for receive, sending values is also not possible, isClosedForSend will return true.

Attributes

Returns

Some if no more values can be received from this channel; Source.receive will throw ChannelClosedException. When closed for receive, sending values is also not possible, isClosedForSend will return true.

def receive(): T

Receive a value from the channel. For a variant which doesn't throw exceptions when the channel is closed, use receiveOrClosed.

Receive a value from the channel. For a variant which doesn't throw exceptions when the channel is closed, use receiveOrClosed.

Attributes

Returns

Either a value of type T, or ChannelClosed, when the channel is closed.

Throws
ChannelClosedException

If the channel is closed (done or in error).

Create a clause which can be used in select. The clause will receive a value from the current channel.

Create a clause which can be used in select. The clause will receive a value from the current channel.

Attributes

Receive a value from the channel. For a variant which throws exceptions when the channel is closed, use receive.

Receive a value from the channel. For a variant which throws exceptions when the channel is closed, use receive.

Attributes

Returns

Either a value of type T, or ChannelClosed, when the channel is closed.

Inherited methods

def alsoTo[U >: T](other: Sink[U])(using Ox, StageCapacity): Source[U]

Attaches the given Sink to this Source, meaning elements that pass through will also be sent to the Sink. If sending to the output channel or the other Sink blocks, no elements will be processed until both channels can receive elements again. The source elements are first sent to the output channel and then, only if the sent is successful, to the other Sink.

Attaches the given Sink to this Source, meaning elements that pass through will also be sent to the Sink. If sending to the output channel or the other Sink blocks, no elements will be processed until both channels can receive elements again. The source elements are first sent to the output channel and then, only if the sent is successful, to the other Sink.

If this source is failed, then failure is passed to the returned channel and the other Sink. If the other sink fails or closes, then failure or closure is passed to the returned channel as well (contrary to alsoToTap where it's ignored).

Value parameters

other

The Sink to which elements from this source will be sent.

Attributes

Returns

A source that emits input elements.

See also

alsoToTap for a version that drops elements when the other Sink is not available for receive.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   val c = Channel.withCapacity[Int](10)
   Source.fromValues(1, 2, 3).alsoTo(c).toList // List(1, 2, 3)
   c.toList // List(1, 2, 3)
 }
Inherited from:
SourceOps
def alsoToTap[U >: T](other: Sink[U])(using Ox, StageCapacity): Source[U]

Attaches the given Sink to this Source, meaning elements that pass through will also be sent to the Sink. If the other Sink is not available for receive, the elements are still sent to returned channel, but not to the other Sink, meaning that some elements may be dropped.

Attaches the given Sink to this Source, meaning elements that pass through will also be sent to the Sink. If the other Sink is not available for receive, the elements are still sent to returned channel, but not to the other Sink, meaning that some elements may be dropped.

If this source is failed, then failure is passed to the returned channel and the other Sink. If the other sink fails or closes, then failure or closure is ignored and it doesn't affect the resulting source (contrary to alsoTo where it's propagated).

Value parameters

other

The Sink to which elements from this source will be sent.

Attributes

Returns

A source that emits input elements.

See also

alsoTo for a version that ensures that elements are sent to both the output and the other Sink.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   val c = Channel.withCapacity[Int](10)
   Source.fromValues(1, 2, 3).alsoToTap(c).toList // List(1, 2, 3)
   c.toList // List(1, 2, 3) but not guaranteed
 }
Inherited from:
SourceOps
def asInputStream(using T <:< Chunk[Byte]): InputStream

Creates a java.io.InputStream out of this Source. The InputStream can read bytes from the underlying channel.

Creates a java.io.InputStream out of this Source. The InputStream can read bytes from the underlying channel.

Attributes

Inherited from:
SourceIOOps
def collectAsView[U](f: PartialFunction[T, U]): Source[U]

Creates a view of this source, where the results of receive will be transformed on the consumer's thread using the given function f. If the function is not defined at an element, the element will be skipped.

Creates a view of this source, where the results of receive will be transformed on the consumer's thread using the given function f. If the function is not defined at an element, the element will be skipped.

The same logic applies to receive clauses created using this source, which can be used in select.

Value parameters

f

The collecting function. Results should not be null.

Attributes

Returns

A source which is a view of this source, with the collecting function applied.

Inherited from:
SourceOps
def concat[U >: T](other: Source[U])(using Ox, StageCapacity): Source[U]

Concatenates this source with the other source. The resulting source will emit elements from this source first, and then from the other source.

Concatenates this source with the other source. The resulting source will emit elements from this source first, and then from the other source.

Value parameters

other

The source to be appended to this source.

Attributes

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1, 2).concat(Source.fromValues(3, 4)).toList // List(1, 2, 3, 4)
 }
Inherited from:
SourceOps
def decodeStringUtf8(using Ox, T <:< Chunk[Byte]): Source[String]

Decodes a stream of chunks of bytes into UTF-8 Strings. This function is able to handle UTF-8 characters encoded on multiple bytes that are split across chunks.

Decodes a stream of chunks of bytes into UTF-8 Strings. This function is able to handle UTF-8 characters encoded on multiple bytes that are split across chunks.

Attributes

Returns

a source of Strings decoded from incoming bytes.

Inherited from:
SourceTextOps
def drain(): Unit

Receives all elements from the channel. Blocks until the channel is done.

Receives all elements from the channel. Blocks until the channel is done.

Attributes

Throws
ChannelClosedException.Error

when there is an upstream error.

Inherited from:
SourceDrainOps
def drainOrError(): Unit | Error

The "safe" variant of drain.

The "safe" variant of drain.

Attributes

Inherited from:
SourceDrainOps
def drop(n: Int)(using Ox, StageCapacity): Source[T]

Drops n elements from this source and forwards subsequent elements to the returned channel.

Drops n elements from this source and forwards subsequent elements to the returned channel.

Value parameters

n

Number of elements to be dropped.

Attributes

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].drop(1).toList          // List()
   Source.fromValues(1, 2, 3).drop(1).toList // List(2 ,3)
   Source.fromValues(1).drop(2).toList       // List()
 }
Inherited from:
SourceOps
def encodeUtf8(using Ox, T <:< String): Source[Chunk[Byte]]

Encodes a source of String in to a source of bytes using UTF-8.

Encodes a source of String in to a source of bytes using UTF-8.

Attributes

Inherited from:
SourceTextOps
def filter(f: T => Boolean)(using Ox, StageCapacity): Source[T]

Attributes

Inherited from:
SourceOps
def filterAsView(f: T => Boolean): Source[T]

Lazily-evaluated filter: Creates a view of this source, where the results of receive will be filtered on the consumer's thread using the given predicate p. For an eager, asynchronous version, see filter.

Lazily-evaluated filter: Creates a view of this source, where the results of receive will be filtered on the consumer's thread using the given predicate p. For an eager, asynchronous version, see filter.

The same logic applies to receive clauses created using this source, which can be used in select.

Value parameters

f

The predicate to use for filtering.

Attributes

Returns

A source which is a view of this source, with the filtering function applied.

Inherited from:
SourceOps
def fold[U](zero: U)(f: (U, T) => U): U

Uses zero as the current value and applies function f on it and a value received from this source. The returned value is used as the next current value and f is applied again with the value received from a source. The operation is repeated until the source is drained.

Uses zero as the current value and applies function f on it and a value received from this source. The returned value is used as the next current value and f is applied again with the value received from a source. The operation is repeated until the source is drained.

Value parameters

f

A binary function (a function that takes two arguments) that is applied to the current value and value received from a source.

zero

An initial value to be used as the first argument to function f call.

Attributes

Returns

Combined value retrieved from running function f on all source elements in a cumulative manner where result of the previous call is used as an input value to the next.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

exception

When function f throws an exception then it is propagated up to the caller.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].fold(0)((acc, n) => acc + n)       // 0
   Source.fromValues(2, 3).fold(5)((acc, n) => acc - n) // 0
 }
Inherited from:
SourceDrainOps
def foldOrError[U](zero: U)(f: (U, T) => U): U | Error

The "safe" variant of fold.

The "safe" variant of fold.

Attributes

Inherited from:
SourceDrainOps
def foreach(f: T => Unit): Unit

Invokes the given function for each received element. Blocks until the channel is done.

Invokes the given function for each received element. Blocks until the channel is done.

Attributes

Throws
ChannelClosedException.Error

When there is an upstream error.

Inherited from:
SourceDrainOps
def foreachOrError(f: T => Unit): Unit | Error

The "safe" variant of foreach.

The "safe" variant of foreach.

Attributes

Inherited from:
SourceDrainOps
def grouped(n: Int)(using Ox, StageCapacity): Source[Seq[T]]

Chunks up the elements into groups of the specified size. The last group may be smaller due to channel being closed. If this source is failed then failure is passed to the returned channel.

Chunks up the elements into groups of the specified size. The last group may be smaller due to channel being closed. If this source is failed then failure is passed to the returned channel.

Value parameters

n

The number of elements in a group.

Attributes

Returns

A source that emits grouped elements.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1, 2, 3, 4, 5, 6, 7).grouped(3).toList // List(Seq(1, 2, 3), Seq(4, 5, 6), Seq(7))
 }
Inherited from:
SourceOps
def groupedWeighted(minWeight: Long)(costFn: T => Long)(using Ox, StageCapacity): Source[Seq[T]]

Chunks up the elements into groups that have a cumulative weight greater or equal to the minWeight. The last group may be smaller due to channel being closed. If this source is failed then failure is passed to the returned channel.

Chunks up the elements into groups that have a cumulative weight greater or equal to the minWeight. The last group may be smaller due to channel being closed. If this source is failed then failure is passed to the returned channel.

Upstream error or exception thrown by costFn will result in this Source failing with that error.

Value parameters

costFn

The function that calculates the weight of an element.

minWeight

The minimum cumulative weight of elements in a group.

Attributes

Returns

A source that emits grouped elements.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1, 2, 3, 4, 5, 6, 7).groupedWeighted(10)(n => n * 2).toList // List(Seq(1, 2, 3), Seq(4, 5), Seq(6), Seq(7))
 }
Inherited from:
SourceOps
def groupedWeightedWithin(minWeight: Long, duration: FiniteDuration)(costFn: T => Long)(using Ox, StageCapacity): Source[Seq[T]]

Chunks up the elements into groups received within a time window or limited by the cumulative weight being greater or equal to the minWeight, whatever happens first. The timeout is reset after a group is emitted. If timeout expires and the buffer is empty, nothing is emitted. As soon as a new element is received, the source will emit it as a single-element group and reset the timer.

Chunks up the elements into groups received within a time window or limited by the cumulative weight being greater or equal to the minWeight, whatever happens first. The timeout is reset after a group is emitted. If timeout expires and the buffer is empty, nothing is emitted. As soon as a new element is received, the source will emit it as a single-element group and reset the timer.

Upstream error or exception thrown by costFn will result in this Source failing with that error.

Value parameters

costFn

The function that calculates the weight of an element.

duration

The time window in which the elements are grouped.

minWeight

The minimum cumulative weight of elements in a group if no timeout happens.

Attributes

Returns

A source that emits grouped elements.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   val c = StageCapacity.newChannel[Int]
   fork {
     c.send(1)
     c.send(2)
     sleep(200.millis)
     c.send(3)
     c.send(4)
     c.send(5)
     c.send(6)
     c.done()
   }
   c.groupedWeightedWithin(10, 100.millis)(n => n * 2).toList // List(Seq(1, 2), Seq(3, 4), Seq(5), Seq(6))
 }
Inherited from:
SourceOps
def groupedWithin(n: Int, duration: FiniteDuration)(using Ox, StageCapacity): Source[Seq[T]]

Chunks up the elements into groups received within a time window or limited by the specified number of elements, whatever happens first. The timeout is reset after a group is emitted. If timeout expires and the buffer is empty, nothing is emitted. As soon as a new element is received, the source will emit it as a single-element group and reset the timer.

Chunks up the elements into groups received within a time window or limited by the specified number of elements, whatever happens first. The timeout is reset after a group is emitted. If timeout expires and the buffer is empty, nothing is emitted. As soon as a new element is received, the source will emit it as a single-element group and reset the timer.

If this source is failed then failure is passed to the returned channel.

Value parameters

duration

The time window in which the elements are grouped.

n

The maximum number of elements in a group.

Attributes

Returns

A source that emits grouped elements.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   val c = StageCapacity.newChannel[Int]
   fork {
     c.send(1)
     c.send(2)
     sleep(200.millis)
     c.send(3)
     c.send(4)
     c.send(5)
     c.send(6)
     c.done()
   }
   c.groupedWithin(3, 100.millis).toList // List(Seq(1, 2), Seq(3, 4, 5), Seq(6))
 }
Inherited from:
SourceOps
def headOption(): Option[T]

Returns the first element from this source wrapped in Some or None when this source is empty. Note that headOption is not an idempotent operation on source as it receives elements from it.

Returns the first element from this source wrapped in Some or None when this source is empty. Note that headOption is not an idempotent operation on source as it receives elements from it.

Attributes

Returns

A Some(first element) if source is not empty or None otherwise.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].headOption()  // None
   val s = Source.fromValues(1, 2)
   s.headOption()                  // Some(1)
   s.headOption()                  // Some(2)
 }
Inherited from:
SourceOps
def interleave[U >: T](other: Source[U], segmentSize: Int, eagerComplete: Boolean)(using Ox, StageCapacity): Source[U]

Sends a given number of elements (determined byc segmentSize) from this source to the returned channel, then sends the same number of elements from the other source and repeats. The order of elements in both sources is preserved.

Sends a given number of elements (determined byc segmentSize) from this source to the returned channel, then sends the same number of elements from the other source and repeats. The order of elements in both sources is preserved.

If one of the sources is done before the other, the behavior depends on the eagerCancel flag. When set to true, the returned channel is completed immediately, otherwise the remaining elements from the other source are sent to the returned channel.

Must be run within a scope, since a child fork is created which receives from both sources and sends to the resulting channel.

Value parameters

eagerComplete

If true, the returned channel is completed as soon as either of the sources completes. If false, the remaining elements of the non-completed source are sent downstream.

other

The source whose elements will be interleaved with the elements of this source.

segmentSize

The number of elements sent from each source before switching to the other one. Default is 1.

Attributes

Returns

A source to which the interleaved elements from both sources would be sent.

Example
 scala>
 import ox.*
 import ox.channels.Source
 supervised {
   val s1 = Source.fromValues(1, 2, 3, 4, 5, 6, 7)
   val s2 = Source.fromValues(10, 20, 30, 40)
   s1.interleave(s2, segmentSize = 2).toList
 }
 scala> val res0: List[Int] = List(1, 2, 10, 20, 3, 4, 30, 40, 5, 6, 7)
Inherited from:
SourceOps
def intersperse[U >: T](start: U, inject: U, end: U)(using Ox, StageCapacity): Source[U]

Intersperses this source with start, end and provided elements and forwards it to the returned channel.

Intersperses this source with start, end and provided elements and forwards it to the returned channel.

Value parameters

end

An element to be appended to the end of the stream.

inject

An element to be injected between the stream elements.

start

An element to be prepended to the stream.

Attributes

Returns

A source, onto which elements will be injected.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[String].intersperse("[", ", ", "]").toList            // List([, ])
   Source.fromValues("foo").intersperse("[", ", ", "]").toList        // List([, foo, ])
   Source.fromValues("foo", "bar").intersperse("[", ", ", "]").toList // List([, foo, ", ", bar, ])
 }
Inherited from:
SourceOps
def intersperse[U >: T](inject: U)(using Ox, StageCapacity): Source[U]

Intersperses this source with provided element and forwards it to the returned channel.

Intersperses this source with provided element and forwards it to the returned channel.

Value parameters

inject

An element to be injected between the stream elements.

Attributes

Returns

A source, onto which elements will be injected.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[String].intersperse(", ").toList            // List()
   Source.fromValues("foo").intersperse(", ").toList        // List(foo)
   Source.fromValues("foo", "bar").intersperse(", ").toList // List(foo, ", ", bar)
 }
Inherited from:
SourceOps
def last(): T

Returns the last element from this source or throws NoSuchElementException when this source is empty. In case when receiving an element fails then ChannelClosedException.Error exception is thrown. Note that last is a terminal operation leaving the source in ChannelClosed.Done state.

Returns the last element from this source or throws NoSuchElementException when this source is empty. In case when receiving an element fails then ChannelClosedException.Error exception is thrown. Note that last is a terminal operation leaving the source in ChannelClosed.Done state.

Attributes

Returns

A last element if source is not empty or throws otherwise.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

NoSuchElementException

When this source is empty.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].last()        // throws NoSuchElementException("cannot obtain last element from an empty source")
   val s = Source.fromValues(1, 2)
   s.last()                        // 2
   s.receive()                     // ChannelClosed.Done
 }
Inherited from:
SourceDrainOps
def lastOption(): Option[T]

Returns the last element from this source wrapped in Some or None when this source is empty. Note that lastOption is a terminal operation leaving the source in ChannelClosed.Done state.

Returns the last element from this source wrapped in Some or None when this source is empty. Note that lastOption is a terminal operation leaving the source in ChannelClosed.Done state.

Attributes

Returns

A Some(last element) if source is not empty or None otherwise.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].lastOption()  // None
   val s = Source.fromValues(1, 2)
   s.lastOption()                  // Some(2)
   s.receive()                     // ChannelClosed.Done
 }
Inherited from:
SourceDrainOps
def lastOptionOrError(): Option[T] | Error

The "safe" variant of lastOption.

The "safe" variant of lastOption.

Attributes

Inherited from:
SourceDrainOps
def lines(charset: Charset)(using Ox, T <:< Chunk[Byte]): Source[String]

Transforms a Source of byte chunks such that each emitted String is a text line from the input.

Transforms a Source of byte chunks such that each emitted String is a text line from the input.

Value parameters

charset

the charset to use for decoding the bytes into text.

Attributes

Returns

a Source emitting lines read from the input byte chunks, assuming they represent text.

Inherited from:
SourceTextOps
def linesUtf8(using Ox, T <:< Chunk[Byte]): Source[String]

Transforms a Source of byte chunks such that each emitted String is a text line from the input decoded using UTF-8 charset.

Transforms a Source of byte chunks such that each emitted String is a text line from the input decoded using UTF-8 charset.

Attributes

Returns

a Source emitting lines read from the input byte chunks, assuming they represent text.

Inherited from:
SourceTextOps
def map[U](f: T => U)(using Ox, StageCapacity): Source[U]

Applies the given mapping function f to each element received from this source, and sends the results to the returned channel.

Applies the given mapping function f to each element received from this source, and sends the results to the returned channel.

Errors from this channel are propagated to the returned channel. Any exceptions that occur when invoking f are propagated as errors to the returned channel as well.

Must be run within a scope, as a child fork is created, which receives from this source and sends the mapped values to the resulting one.

For a lazily-evaluated version, see mapAsView.

Value parameters

f

The mapping function.

Attributes

Returns

A source, onto which results of the mapping function will be sent.

Inherited from:
SourceOps
def mapAsView[U](f: T => U): Source[U]

Lazily-evaluated map: creates a view of this source, where the results of receive will be transformed on the consumer's thread using the given function f. For an eager, asynchronous version, see map.

Lazily-evaluated map: creates a view of this source, where the results of receive will be transformed on the consumer's thread using the given function f. For an eager, asynchronous version, see map.

The same logic applies to receive clauses created using this source, which can be used in select.

Value parameters

f

The mapping function. Results should not be null.

Attributes

Returns

A source which is a view of this source, with the mapping function applied.

Inherited from:
SourceOps
def mapConcat[U](f: T => IterableOnce[U])(using Ox, StageCapacity): Source[U]

Applies the given mapping function f, to each element received from this source, transforming it into an Iterable of results, then sends the results one by one to the returned channel. Can be used to unfold incoming sequences of elements into single elements.

Applies the given mapping function f, to each element received from this source, transforming it into an Iterable of results, then sends the results one by one to the returned channel. Can be used to unfold incoming sequences of elements into single elements.

Value parameters

f

A function that transforms the element from this source into a pair of the next state into an scala.collection.IterableOnce of results which are sent one by one to the returned channel. If the result of f is empty, nothing is sent to the returned channel.

Attributes

Returns

A source to which the results of applying f to the elements from this source would be sent.

Example
 scala>
 import ox.*
 import ox.channels.Source
 supervised {
   val s = Source.fromValues(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
   s.mapConcat(identity)
 }
 scala> val res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
Inherited from:
SourceOps
def mapPar[U](parallelism: Int)(f: T => U)(using Ox, StageCapacity): Source[U]

Applies the given mapping function f to each element received from this source, and sends the results to the returned channel. At most parallelism invocations of f are run in parallel.

Applies the given mapping function f to each element received from this source, and sends the results to the returned channel. At most parallelism invocations of f are run in parallel.

The mapped results are sent to the returned channel in the same order, in which inputs are received from this source. In other words, ordering is preserved.

Errors from this channel are propagated to the returned channel. Any exceptions that occur when invoking f are propagated as errors to the returned channel as well, and result in interrupting any mappings that are in progress.

Must be run within a scope, as child forks are created, which receive from this source, send to the resulting one, and run the mappings.

Value parameters

f

The mapping function.

parallelism

An upper bound on the number of forks that run in parallel. Each fork runs the function f on a single element of the source.

Attributes

Returns

A source, onto which results of the mapping function will be sent.

Inherited from:
SourceOps
def mapParUnordered[U](parallelism: Int)(f: T => U)(using Ox, StageCapacity): Source[U]

Attributes

Inherited from:
SourceOps
def mapStateful[S, U](initializeState: () => S)(f: (S, T) => (S, U), onComplete: S => Option[U])(using Ox, StageCapacity): Source[U]

Applies the given mapping function f, using additional state, to each element received from this source, and sends the results to the returned channel. Optionally sends an additional element, possibly based on the final state, to the returned channel once this source is done.

Applies the given mapping function f, using additional state, to each element received from this source, and sends the results to the returned channel. Optionally sends an additional element, possibly based on the final state, to the returned channel once this source is done.

The initializeState function is called once when statefulMap is called.

The onComplete function is called once when this source is done. If it returns a non-empty value, the value will be sent to the returned channel, while an empty value will be ignored.

Value parameters

f

A function that transforms the element from this source and the state into a pair of the next state and the result which is sent sent to the returned channel.

initializeState

A function that initializes the state.

onComplete

A function that transforms the final state into an optional element sent to the returned channel. By default the final state is ignored.

Attributes

Returns

A source to which the results of applying f to the elements from this source would be sent.

Example
 scala>
 import ox.*
 import ox.channels.Source
 supervised {
   val s = Source.fromValues(1, 2, 3, 4, 5)
   s.mapStateful(() => 0)((sum, element) => (sum + element, sum), Some.apply)
 }
 scala> val res0: List[Int] = List(0, 1, 3, 6, 10, 15)
Inherited from:
SourceOps
def mapStatefulConcat[S, U](initializeState: () => S)(f: (S, T) => (S, IterableOnce[U]), onComplete: S => Option[U])(using Ox, StageCapacity): Source[U]

Applies the given mapping function f, using additional state, to each element received from this source, and sends the results one by one to the returned channel. Optionally sends an additional element, possibly based on the final state, to the returned channel once this source is done.

Applies the given mapping function f, using additional state, to each element received from this source, and sends the results one by one to the returned channel. Optionally sends an additional element, possibly based on the final state, to the returned channel once this source is done.

The initializeState function is called once when statefulMap is called.

The onComplete function is called once when this source is done. If it returns a non-empty value, the value will be sent to the returned channel, while an empty value will be ignored.

Value parameters

f

A function that transforms the element from this source and the state into a pair of the next state and a scala.collection.IterableOnce of results which are sent one by one to the returned channel. If the result of f is empty, nothing is sent to the returned channel.

initializeState

A function that initializes the state.

onComplete

A function that transforms the final state into an optional element sent to the returned channel. By default the final state is ignored.

Attributes

Returns

A source to which the results of applying f to the elements from this source would be sent.

Example
 scala>
 import ox.*
 import ox.channels.Source
 supervised {
   val s = Source.fromValues(1, 2, 2, 3, 2, 4, 3, 1, 5)
   // deduplicate the values
   s.mapStatefulConcat(() => Set.empty[Int])((s, e) => (s + e, Option.unless(s.contains(e))(e)))
 }
 scala> val res0: List[Int] = List(1, 2, 3, 4, 5)
Inherited from:
SourceOps
def merge[U >: T](other: Source[U])(using Ox, StageCapacity): Source[U]

Attributes

Inherited from:
SourceOps
def orElse[U >: T](alternative: Source[U])(using Ox, StageCapacity): Source[U]

If this source has no elements then elements from an alternative source are emitted to the returned channel. If this source is failed then failure is passed to the returned channel.

If this source has no elements then elements from an alternative source are emitted to the returned channel. If this source is failed then failure is passed to the returned channel.

Value parameters

alternative

An alternative source of elements used when this source is empty.

Attributes

Returns

A source that emits either elements from this source or from alternative (when this source is empty).

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1).orElse(Source.fromValues(2, 3)).toList // List(1)
   Source.empty.orElse(Source.fromValues(2, 3)).toList         // List(2, 3)
 }
Inherited from:
SourceOps
def pipeTo(sink: Sink[T]): Unit

Passes each received element from this channel to the given sink. Blocks until the channel is done. When the channel is done or there's an error, propagates the closed status downstream and returns.

Passes each received element from this channel to the given sink. Blocks until the channel is done. When the channel is done or there's an error, propagates the closed status downstream and returns.

Attributes

Inherited from:
SourceDrainOps
def prepend[U >: T](other: Source[U])(using Ox, StageCapacity): Source[U]

Prepends other source to this source. The resulting source will emit elements from other source first, and then from the this source.

Prepends other source to this source. The resulting source will emit elements from other source first, and then from the this source.

Value parameters

other

The source to be prepended to this source.

Attributes

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1, 2).prepend(Source.fromValues(3, 4)).toList // List(3, 4, 1, 2)
 }
Inherited from:
SourceOps
def reduce[U >: T](f: (U, U) => U): U

Uses the first and the following (if available) elements from this source and applies function f on them. The returned value is used as the next current value and f is applied again with the value received from this source. The operation is repeated until this source is drained. This is similar operation to fold but it uses the first source element as zero.

Uses the first and the following (if available) elements from this source and applies function f on them. The returned value is used as the next current value and f is applied again with the value received from this source. The operation is repeated until this source is drained. This is similar operation to fold but it uses the first source element as zero.

Value parameters

f

A binary function (a function that takes two arguments) that is applied to the current and next values received from this source.

Attributes

Returns

Combined value retrieved from running function f on all source elements in a cumulative manner where result of the previous call is used as an input value to the next.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

NoSuchElementException

When this source is empty.

exception

When function f throws an exception then it is propagated up to the caller.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].reduce(_ + _)    // throws NoSuchElementException("cannot reduce an empty source")
   Source.fromValues(1).reduce(_ + _) // 1
   val s = Source.fromValues(1, 2)
   s.reduce(_ + _)                    // 3
   s.receive()                        // ChannelClosed.Done
 }
Inherited from:
SourceDrainOps
def sliding(n: Int, step: Int)(using Ox, StageCapacity): Source[Seq[T]]

Creates sliding windows of elements from this source. The window slides by step elements. The last window may be smaller due to channel being closed.

Creates sliding windows of elements from this source. The window slides by step elements. The last window may be smaller due to channel being closed.

If this source is failed then failure is passed to the returned channel.

Value parameters

n

The number of elements in a window.

step

The number of elements the window slides by.

Attributes

Returns

A source that emits grouped elements.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.fromValues(1, 2, 3, 4, 5, 6).sliding(3, 2).toList // List(Seq(1, 2, 3), Seq(3, 4, 5), Seq(5, 6))
 }
Inherited from:
SourceOps
def take(n: Int)(using Ox, StageCapacity): Source[T]

Attributes

Inherited from:
SourceOps
def takeLast(n: Int): List[T]

Returns the list of up to n last elements from this source. Less than n elements is returned when this source contains less elements than requested. The List.empty is returned when takeLast is called on an empty source.

Returns the list of up to n last elements from this source. Less than n elements is returned when this source contains less elements than requested. The List.empty is returned when takeLast is called on an empty source.

Value parameters

n

Number of elements to be taken from the end of this source. It is expected that n >= 0.

Attributes

Returns

A list of up to n last elements from this source.

Throws
ChannelClosedException.Error

When receiving an element from this source fails.

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].takeLast(5)    // List.empty
   Source.fromValues(1).takeLast(0) // List.empty
   Source.fromValues(1).takeLast(2) // List(1)
   val s = Source.fromValues(1, 2, 3, 4)
   s.takeLast(2)                    // List(4, 5)
   s.receive()                      // ChannelClosed.Done
 }
Inherited from:
SourceDrainOps
def takeLastOrError(n: Int): List[T] | Error

The "safe" variant of takeLast.

The "safe" variant of takeLast.

Attributes

Inherited from:
SourceDrainOps
def takeWhile(f: T => Boolean, includeFirstFailing: Boolean)(using Ox, StageCapacity): Source[T]

Transform the source so that it returns elements as long as predicate f is satisfied (returns true). If includeFirstFailing is true, the returned source will additionally return the first element that failed the predicate. After that, the source will complete as Done.

Transform the source so that it returns elements as long as predicate f is satisfied (returns true). If includeFirstFailing is true, the returned source will additionally return the first element that failed the predicate. After that, the source will complete as Done.

Value parameters

f

A predicate function called on incoming elements. If it throws an exception, the result Source will be failed with that exception.

includeFirstFailing

Whether the source should also emit the first element that failed the predicate (false by default).

Attributes

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].takeWhile(_ > 3).toList          // List()
   Source.fromValues(1, 2, 3).takeWhile(_ < 3).toList // List(1, 2)
   Source.fromValues(1, 2, 3, 4).takeWhile(_ < 3, includeFirstFailing = true).toList // List(1, 2, 3)
   Source.fromValues(3, 2, 1).takeWhile(_ < 3).toList // List()
 }
Inherited from:
SourceOps
def tap(f: T => Unit)(using Ox, StageCapacity): Source[T]

Applies the given consumer function f to each element received from this source.

Applies the given consumer function f to each element received from this source.

Errors from this channel are propagated to the returned channel. Any exceptions that occur when invoking f are propagated as errors to the returned channel as well.

Must be run within a scope, as a child fork is created, which receives from this source and sends the mapped values to the resulting one.

Useful for side-effects without result values, like logging and debugging. For a lazily-evaluated version, see tapAsView.

Value parameters

f

The consumer function.

Attributes

Returns

A source, which the elements from the input source are passed to.

Inherited from:
SourceOps
def tapAsView(f: T => Unit): Source[T]

Lazily-evaluated tap: creates a view of this source, where the results of receive will be applied to the given function f on the consumer's thread. Useful for side-effects without result values, like logging and debugging. For an eager, asynchronous version, see tap.

Lazily-evaluated tap: creates a view of this source, where the results of receive will be applied to the given function f on the consumer's thread. Useful for side-effects without result values, like logging and debugging. For an eager, asynchronous version, see tap.

The same logic applies to receive clauses created using this source, which can be used in select.

Value parameters

f

The consumer function.

Attributes

Returns

A source which is a view of this source, with the consumer function applied.

Inherited from:
SourceOps
def throttle(elements: Int, per: FiniteDuration)(using Ox, StageCapacity): Source[T]

Sends elements to the returned channel limiting the throughput to specific number of elements (evenly spaced) per time unit. Note that the element's receive() time is included in the resulting throughput. For instance having throttle(1, 1.second) and receive() taking Xms means that resulting channel will receive elements every 1s + Xms time. Throttling is not applied to the empty source.

Sends elements to the returned channel limiting the throughput to specific number of elements (evenly spaced) per time unit. Note that the element's receive() time is included in the resulting throughput. For instance having throttle(1, 1.second) and receive() taking Xms means that resulting channel will receive elements every 1s + Xms time. Throttling is not applied to the empty source.

Value parameters

elements

Number of elements to be emitted. Must be greater than 0.

per

Per time unit. Must be greater or equal to 1 ms.

Attributes

Returns

A source that emits at most elements per time unit.

Example
 import ox.*
 import ox.channels.Source
 import scala.concurrent.duration.*
 supervised {
   Source.empty[Int].throttle(1, 1.second).toList       // List() returned without throttling
   Source.fromValues(1, 2).throttle(1, 1.second).toList // List(1, 2) returned after 2 seconds
 }
Inherited from:
SourceOps
def toFile(path: Path)(using T <:< Chunk[Byte], IO): Unit

Writes content of this Source to a file.

Writes content of this Source to a file.

Value parameters

path

Path to the target file. If not exists, it will be created.

Attributes

Throws
IOException

if an error occurs when opening the file or during the write process.

Inherited from:
SourceIOOps
def toList: List[T]

Accumulates all elements received from the channel into a list. Blocks until the channel is done.

Accumulates all elements received from the channel into a list. Blocks until the channel is done.

Attributes

Throws
ChannelClosedException.Error

When there is an upstream error.

Inherited from:
SourceDrainOps
def toListOrError: List[T] | Error

The "safe" variant of toList.

The "safe" variant of toList.

Attributes

Inherited from:
SourceDrainOps
def toOutputStream(outputStream: OutputStream)(using T <:< Chunk[Byte], IO): Unit

Writes content of this Source to an java.io.OutputStream.

Writes content of this Source to an java.io.OutputStream.

Value parameters

outputStream

Target OutputStream to write to. Will be closed after finishing the process or on error.

Attributes

Throws
IOException

if an error occurs when writing or closing of the OutputStream.

Inherited from:
SourceIOOps
def transform[U](f: (Iterator[T]) => Iterator[U])(using Ox, StageCapacity): Source[U]

Attributes

Inherited from:
SourceOps
def zip[U](other: Source[U])(using Ox, StageCapacity): Source[(T, U)]

Attributes

Inherited from:
SourceOps
def zipAll[U >: T, V](other: Source[V], thisDefault: U, otherDefault: V)(using Ox, StageCapacity): Source[(U, V)]

Combines elements from this and other sources into tuples handling early completion of either source with defaults.

Combines elements from this and other sources into tuples handling early completion of either source with defaults.

Value parameters

other

A source of elements to be combined with.

otherDefault

A default element to be used in the result tuple when the current source is longer.

thisDefault

A default element to be used in the result tuple when the other source is longer.

Attributes

Example
 import ox.*
 import ox.channels.Source
 supervised {
   Source.empty[Int].zipAll(Source.empty[String], -1, "foo").toList      // List()
   Source.empty[Int].zipAll(Source.fromValues("a"), -1, "foo").toList    // List((-1, "a"))
   Source.fromValues(1).zipAll(Source.empty[String], -1, "foo").toList   // List((1, "foo"))
   Source.fromValues(1).zipAll(Source.fromValues("a"), -1, "foo").toList // List((1, "a"))
 }
Inherited from:
SourceOps