SourceOps

ox.channels.SourceOps
trait SourceOps[+T]

Attributes

Graph
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait Source[T]
trait Channel[T]
class BufferedChannel[T]
class DirectChannel[T]
class CollectSource[T, U]
Self type
Source[T]

Members list

Value members

Concrete methods

def applied[U](f: Source[T] => U): U
def collectAsView[U](f: PartialFunction[T, U]): Source[U]
def concat[U >: T](other: Source[U])(using Ox, StageCapacity): Source[U]
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

when there is an upstream error.

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()
 }
def filter(f: T => Boolean)(using Ox, StageCapacity): Source[T]
def filterAsView(f: T => Boolean): Source[T]
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
 }
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

when there is an upstream error.

def head(): T

Returns the first element from this source or throws NoSuchElementException when this source is empty. In case when receiving an element fails with exception then ChannelClosedException.Error is thrown. Note that head is not an idempotent operation on source as it receives elements from it.

Returns the first element from this source or throws NoSuchElementException when this source is empty. In case when receiving an element fails with exception then ChannelClosedException.Error is thrown. Note that head is not an idempotent operation on source as it receives elements from it.

Attributes

Returns

A first 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].head()        // throws NoSuchElementException("cannot obtain head element from an empty source")
   val s = Source.fromValues(1, 2)
   s.head()                        // 1
   s.head()                        // 2
 }
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)
 }
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)
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)
 }
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, ])
 }
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
 }
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
 }
def map[U](f: T => U)(using Ox, StageCapacity): Source[U]
def mapAsView[U](f: T => U): Source[U]
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.

def mapParUnordered[U](parallelism: Int)(f: T => U)(using Ox, StageCapacity): Source[U]
def mapStateful[S, U >: T](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)
def mapStatefulConcat[S, U >: T](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)
def merge[U >: T](other: Source[U])(using Ox, StageCapacity): Source[U]
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)
 }
def pipeTo(sink: Sink[T]): Unit

Passes each received element from this channel to the given sink. Blocks until the channel is done.

Passes each received element from this channel to the given sink. Blocks until the channel is done.

Attributes

Throws
ChannelClosedException

when there is an upstream error, or when the sink is closed.

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
 }
def take(n: Int)(using Ox, StageCapacity): Source[T]
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
 }
def takeWhile(f: T => Boolean)(using Ox, StageCapacity): Source[T]

Sends elements to the returned channel until predicate f is satisfied (returns true). Note that when the predicate f is not satisfied (returns false), subsequent elements are dropped even if they could still satisfy it.

Sends elements to the returned channel until predicate f is satisfied (returns true). Note that when the predicate f is not satisfied (returns false), subsequent elements are dropped even if they could still satisfy it.

Value parameters

f

A predicate function.

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(3, 2, 1).takeWhile(_ < 3).toList // List()
 }
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.*
 scoped {
   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
 }
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

when there is an upstream error.

def transform[U](f: Iterator[T] => Iterator[U])(using Ox, StageCapacity): Source[U]
def zip[U](other: Source[U])(using Ox, StageCapacity): Source[(T, U)]
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"))
 }