🏝️ Koh.js - Merge Island

This example demonstrates the use of:


import { island } from './static/koh-js/core/index.js'
import {
    fromValue,
    fromInterval,
    fromMerge,
} from './static/koh-js/stream/index.js'

island('merge-island', k => {
    const a$ = fromValue(0)
    const b$ = fromValue(0)
    const timer$ = fromInterval(1000)
    const paused$ = fromValue(false)

    timer$.subscribe({
        pause() {
            paused$.next(true)
        },
        resume() {
            paused$.next(false)
        },
    })

    // Combine streams into one
    const sum$ = fromMerge(a$, b$, timer$).pipe(
        // Compute sum automatically
        vals => vals.reduce((prev, curr) => prev + curr, 0)
    )
    // Sync each value to its UI element
    k.sync('#a', a$)
    k.sync('#b', b$)
    k.sync('#timer', timer$)
    k.sync('#timer-p', paused$, (el, value) => {
        el.style.color = value ? 'lightgray' : 'teal'
    })

    k.sync('#sum', sum$, (el, val) => {
        el.textContent = val
        el.style.color = val % 2 === 0 ? 'teal' : 'coral'
    })

    // Buttons
    k.on('[name="inc-a"]', 'click', () => a$.next(c => c + 1))
    k.on('[name="inc-b"]', 'click', () => b$.next(c => c + 1))
    // Pause /resume
    k.on('[name="pause-timer"]', 'click', () => timer$.pause())
    k.on('[name="resume-timer"]', 'click', () => timer$.resume())
})
 
                

<merge-island />

Stream interval: 0

Stream A: 0

Stream B: 0

Merged=> Sum (A + B + interval): 0