Skip to content

Sources

Eugene Ghanizadeh edited this page Dec 2, 2021 · 11 revisions
interface Source<T> {
  connect(sink: Sink<T>)
}

Sources are producers of data and events. Sources can be listenable, which means they would push values on their own, pullable, which means they wait for sinks to request data before pushing, or a mixture of both. Here is a quick overview of source factories in streamlets package:


Creates a listenable source that synchronously emits given values.

// emits 1, 2 & 3 synchronously
of(1, 2, 3)

Creates a pullable source from given iterable (array, generator, iterator).

// emits 1, 2 & 3 when pulled
iterable([1, 2, 3])

Creates a timer that emits increasing integers at given periods.

// emits every second
interval(1000)

Turns a Promise into a source.

// emits when `asyncTask()` is done.
promise(asyncTask())

Creates a stream from DOM events.

// emits when `btn` is clicked.
event(btn, 'click')

Creates a stream from given http(s) request. Is listenable, but can be pulled to request again.

// emits results from `https://my.api`
fetch('https://my.api')

A shared source that is also a sink and can be manually controlled.

new Subject()

Concats streams (similar to concatenating arrays).

// emits 1, 2, 3 synchronously.
// then emits 4, 5, 6 when pulled.
// then emits 7, 8, 9, ... every second.
concat(
  of(1, 2, 3),
  iterable([4, 5, 6]),
  map(interval(1000), x => x + 7)
)
           a:  ---1--2--3--|
           b:  ---x--y--z--|
concat(a, b):  ---1--2--3-----x--y--z--|

Merges given streams into one.

// emits every 2 seconds, OR when `btn` is clicked.
merge(
  interval(2000),
  event(btn, 'click')
)
          a:  ------1------2-----3--|
          b:  -x-------y------z--------w-|
merge(a, b):  -x----1--y---2--z--3-----w-|

Combines given streams, emitting arrays of latest values of each.

// emits every 2 seconds AND when user inputs text into `input`,
// in the form of `[2, 'hellow']`
combine(
  interval(2000),
  map(
    event(input, 'input'),
    () => input.value
  )
)
            a:  ---1 ------2 -------3 --|
            b:  -x ---y -------z ----------w ---|
combine(a, b):  ---1x-1y---2y--2z---3z-----3w---|

Creates expressions of sources.

const a = interval(1000)
const b = interval(500)

// when either a or b emit, emits the sum of their latest values.
expr($ => $(a) + $(b))
                     a:  -----1------2-----3-|
                     b:  -2-------0-----3------6--|
expr($ => $(a) + $(b)):  -----3---1--2--5--6---9--|

Like expr(), but only re-calculates when sources emit different values from last run, and only emits when the result of the calculation is different from last run.

                     a:  -----4------6-----3-|
                     b:  -2-------2-----4------6--|
memo($ => $(a) % $(b)):  -----0---------2--3------|

💡 Use memo() instead of expr() when performing expensive calculations.





Clone this wiki locally