Skip to content
Eugene Ghanizadeh edited this page Oct 24, 2021 · 2 revisions
function merge<T>(...sources: Source<T>[]): Source<T>
          a:  ------1------2-----3--|
          b:  -x-------y------z--------w-|
merge(a, b):  -x----1--y---2--z--3-----w-|

Merges given sources together, emitting everything that each one emits. For example, in the code below, input from given <input/> will be displayed on the <div/>, but it gets interrupted with messages from the timer:

HTML Code
<input type="text" placeholder="Type something ..." />
<div></div>
import { pipe, event, interval, filter,
  merge, observe, tap, map } from 'streamlets'

const $input = document.querySelector('input')
const $div = document.querySelector('div')

// create a timer that reminds you
// of elapsed time every 3 seconds
const timer = pipe(
  interval(1000),
  filter((x) => x % 3 === 0),
  map((x) => `${x} seconds have passed!`)
)

// get the input value
const input = pipe(
  event($input, 'input'),
  map(() => $input.value)
)

// merge the two streams
pipe(
  merge(timer, input),
  tap((x) => ($div.textContent = x)),
  observe
)

Try in Sandbox

💡 If one of the sources ends due to an error, the whole stream will be closed. If a source ends without an error, the merged stream will continue until all sources end their corresponding substreams.





Clone this wiki locally