Skip to content
PingidPublic

About

A minimal reactive programming library with Observables, Subjects, and composable

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

@lickle/rx

A minimal reactive programming library with Observables, Subjects, and composable operators.

Build Status Build Size Version Downloads

Install

npm install @lickle/rx

Quick Start

import { of, map, filter } from '@lickle/rx'

const doubled = of(1, 2, 3, 4, 5).pipe(
  filter((x) => x % 2 === 0),
  map((x) => x * 2),
)

doubled.subscribe((value) => console.log(value))
// Output: 4, 8

Every operator is a plain function from Observable to Observable, so pipe from @lickle/rx/util is equivalent and composes with anything else:

import { pipe } from '@lickle/rx/util'

const doubled = pipe(
  of(1, 2, 3, 4, 5),
  filter((x) => x % 2 === 0),
  map((x) => x * 2),
)

Core Concepts

Observable

An Observable is a function that accepts an Observer and returns an unsubscribe function. It also carries pipe and subscribe for convenience:

type Unsubscribe = () => void

type Observer<T, E = unknown> = {
  next: (value: T) => void
  error: (err: E) => void
  complete: () => void
}

interface Observable<T, E = unknown> {
  (observer: Observer<T, E>): Unsubscribe
  pipe: (...operators) => Observable<unknown>
  subscribe: (observer: ((value: T) => void) | Partial<Observer<T, E>>) => Unsubscribe
}

Observables are lazy — nothing runs until you subscribe. subscribe accepts a bare callback or a partial observer, and fills in the handlers you omit:

const unsub = source.subscribe(console.log)

const unsub = source.subscribe({
  next: (value) => console.log(value),
  error: (err) => console.error(err),
  complete: () => console.log('done'),
})

unsub() // tear down

Creating your own

Wrap a subscribe callback with observable(). This attaches pipe and subscribe, so a bare function is not itself an Observable:

import { observable } from '@lickle/rx'

const clicks = observable<MouseEvent>((observer) => {
  const handler = (e: MouseEvent) => observer.next(e)
  document.addEventListener('click', handler)
  return () => document.removeEventListener('click', handler)
})

Subject

Subjects are observables you can drive manually. They multicast to every subscriber:

import { subject } from '@lickle/rx'

const clicks = subject<number>()

clicks.subscribe((x) => console.log('Subscriber 1:', x))
clicks.subscribe((x) => console.log('Subscriber 2:', x))

clicks.next(42) // both subscribers receive 42

Constructors

import { of, from, interval, timer, empty, never, fromAsync, fromDomEvent } from '@lickle/rx'

of(1, 2, 3) // from values
from([1, 2, 3]) // from an Array, Iterable, AsyncIterable, Promise or Observable
from(fetch('/api/data')) // from a Promise
fromAsync((signal) => fetch('/api/data', { signal })) // aborts on unsubscribe
interval(1000) // emit every second
timer(1000, 500) // emit after 1s, then every 500ms
empty() // complete immediately
never() // never emit
fromDomEvent(button, 'click') // from DOM events

Operators

  • Transform: map, scan, reduce, switchMap, mergeMap, concatMap, exhaustMap
  • Filter: filter, take, takeUntil, takeWhile, skip, skipUntil, skipWhile, distinct
  • Time: debounce, throttle, delay, buffer
  • Combine: withLatest, mergeWith, startWith, pairwise, withPrevious
  • Errors: catchError, finalize, retry, timeout
  • Side effects: tap, effect
  • Multicasting: share, shareReplay, shareReplayByKey
  • Scheduling: schedule

RxJS names (debounceTime, throttleTime, bufferTime, distinctUntilChanged, withLatestFrom, observeOn) remain available as deprecated aliases.

import { subject, map, debounce, switchMap, catchError, of } from '@lickle/rx'

const query = subject<string>()

const results = query.pipe(
  debounce(300),
  map((q) => q.trim()),
  switchMap((q) => fetch(`/api/search?q=${q}`).then((r) => r.json())),
  catchError(() => of([])),
)

Combinators

import { merge, combineLatest, zip, concat, race } from '@lickle/rx'

merge(a, b, c) // interleave all emissions
combineLatest(a, b) // emits [latestA, latestB] once both have emitted
zip(a, b) // pair values by index
concat(a, b) // subscribe to b once a completes
race(a, b) // mirror whichever emits first

All five complete once their sources do: merge and combineLatest when every source has completed, zip when the shortest ends, concat after the last one, race with the winner.


Subjects

import { subject, replaySubject, behaviorSubject, replayByKeySubject } from '@lickle/rx'

subject<number>() // multicast only
replaySubject<number>(3) // replay last 3 values to new subscribers
behaviorSubject(0) // holds a current value, exposes getValue()
replayByKeySubject((e) => e.type) // replay latest value per key

Schedulers

Operators that deal with time accept a Scheduler, which makes them testable and lets you choose where work runs.

import { timer, take, schedule, animationFrameScheduler, createVirtualScheduler } from '@lickle/rx'

// Render on animation frames
data.pipe(schedule(animationFrameScheduler)).subscribe(renderToCanvas)

// Run a timed sequence instantly in tests
const scheduler = createVirtualScheduler()
const seen: number[] = []
timer(1000, 1000, scheduler)
  .pipe(take(3))
  .subscribe((x) => seen.push(x))
scheduler.flush()

Available: asyncScheduler, asapScheduler, animationFrameScheduler, idleScheduler, createQueueScheduler, createVirtualScheduler.

debounce, throttle, delay, buffer, interval, timer and schedule all take a scheduler as their last argument, defaulting to asyncScheduler.


Cancellation

Unsubscribing tears down the whole chain. Operators that stop early — take, takeWhile, takeUntil — also signal upstream, so a synchronous source stops mid-emission instead of running to completion:

pipe(from(hugeArray), take(2)).subscribe(console.log) // reads two elements, not the whole array

This works through the synchronous operators (map, filter, scan, tap, and friends) and the combinators. share and shareReplay deliberately stop the signal, since one subscriber leaving must not cancel a source that others are still using.


Browser

@lickle/rx/browser wraps the platform APIs that are awkward to unsubscribe from by hand. Nothing touches a global until you subscribe, so the module is safe to import during server-side rendering.

import {
  fromDomEvent,
  fromMutations,
  fromResize,
  fromIntersection,
  fromMediaQuery,
  fromVisibility,
  fromOnline,
  fromAnimationFrame,
  fromAbortSignal,
} from '@lickle/rx/browser'

fromDomEvent(button, 'click') // typed DOM events
fromMutations(list, { childList: true }) // MutationObserver records
fromResize(el) // ResizeObserver entries
fromIntersection(el, { threshold: 0.5 }) // IntersectionObserver entries
fromMediaQuery('(prefers-color-scheme: dark)') // current match, then changes
fromVisibility() // 'visible' | 'hidden'
fromOnline() // navigator.onLine
fromAnimationFrame() // frame timestamps
fromAbortSignal(controller.signal) // emits the reason, then completes

fromMediaQuery, fromVisibility and fromOnline emit the current value on subscribe and then every change, so there is no initial-state gap to paper over:

const width$ = fromResize(el).pipe(
  map(([entry]) => entry.contentRect.width),
  distinct(),
)

fromAbortSignal pairs with takeUntil to tie a stream to an existing AbortController:

const data$ = source$.pipe(takeUntil(fromAbortSignal(controller.signal)))

Entry Points

Import everything from @lickle/rx, or reach for a single module to keep bundles tight:

Import Contents
@lickle/rx Everything below
@lickle/rx/observable Observable, Observer, observable, subscribe
@lickle/rx/constructor of, from, interval, timer, empty, never, ...
@lickle/rx/operator map, filter, switchMap, share, ...
@lickle/rx/combinator merge, combineLatest, zip, concat, race
@lickle/rx/subject subject, replaySubject, behaviorSubject, ...
@lickle/rx/scheduler asyncScheduler, createVirtualScheduler, ...
@lickle/rx/util pipe, flow, dispose
@lickle/rx/browser fromDomEvent, fromMutations, fromResize, ...

Interop

Interop goes both ways via Symbol.observable.

Every Observable implements it by returning itself, so libraries that speak the protocol (RxJS and friends) consume one directly — no wrapper needed:

import { of } from '@lickle/rx'
import { from as rxFrom } from 'rxjs'

const rxjs$ = rxFrom(of(1, 2, 3))

And from accepts any foreign source that implements it:

import { from, map } from '@lickle/rx'
import { interval as rxInterval } from 'rxjs'

const ticks$ = from(rxInterval(1000)).pipe(map((n) => n * 2))

Values, completion, errors, and unsubscription all cross the boundary, so terminating an RxJS pipeline tears down the @lickle/rx source and vice versa.


License

MIT © Dan Beaven

About

A minimal reactive programming library with Observables, Subjects, and composable

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages