import { isPromise } from "@implab/core-amd/safe"; import { Unsubscribable, Producer, FusedSink, Observable, Subscribable } from "./observable/interfaces"; import { ObservableImpl } from "./observable/ObservableImpl"; export const isUnsubscribable = (v: unknown): v is Unsubscribable => v !== null && v !== undefined && typeof (v as Unsubscribable).unsubscribe === "function"; export const isSubscribable = (v: unknown): v is Subscribable => v !== null && v !== undefined && typeof (v as Subscribable).subscribe === "function"; const noop = () => { }; /** Wraps the producer to handle tear down logic and subscription management * * The resulting producer will invoke cleanup logic on error or complete events * and will prevent calling of any method from the sink. * * @param producer The producer to wrap * @returns The wrapper producer */ const fuse = (producer: Producer) => ({ next, error, complete }: FusedSink) => { let done = false; let cleanup = noop; const _fin = (fn: (...args: A) => void) => (...args: A) => done ? void (0) : (done = true, cleanup(), fn(...args)); const _fin0 = () => done ? void (0) : (done = true, cleanup()); const safeSink = { next: (value: T) => { !done && next(value); }, error: _fin(error), complete: _fin(complete), isClosed: () => done }; // call the producer cleanup = producer(safeSink) ?? noop; // if the producer throws exception bypass it to the caller rather then to // the sink. This is a feature. // if the producer completed the sequence immediately call the cleanup in place return done ? cleanup() : _fin0; }; export const observe = (producer: Producer): Observable => new ObservableImpl(fuse(producer)); /** Converts an array to the observable sequence of its elements. */ export const ofArray = (items: T[]) => new ObservableImpl( ({ next, complete }) => ( items.forEach(next), complete() ) ); /** Converts a subscribable to the observable */ export const ofSubscribable = (subscribable: Subscribable) => observe(sink => { const subscription = subscribable.subscribe(sink); return () => subscription.unsubscribe(); }); const of1 = (item: T | PromiseLike) => observe( ({ next, error, complete }) => isPromise(item) ? void item.then( v => (next(v), complete()), error ) : (next(item), complete()) ); /** Converts a list of parameter values to the observable sequence. The * order of elements in the list will be preserved in the resulting sequence. */ export const of = (...items: (T | PromiseLike)[]) => items.length === 1 ? of1(items[0]) : observe( ({ next, error, complete, isClosed }) => { const n = items.length; const _next = (start: number) => { if (start > 0 && isClosed()) // when resumed return; for (let i = start; i < n; i++) { const r = items[i]; if (isPromise(r)) { r.then(v => (next(v), _next(i + 1)), error); return; // suspend } else { next(r); } } complete(); }; _next(0); } ); export const empty = new ObservableImpl(({ complete }) => complete()); export type * from "./observable/interfaces";