rimmel
Version:
A Streams-Oriented UI library for the Rx.Observable Universe
53 lines (50 loc) • 1.93 kB
JavaScript
import { isObservable, isPromise } from '../types/futures.js';
import { subscriptions } from '../internal-state.js';
import { toListener } from '../utils/to-listener.js';
/**
* Return the "callable" part of an entity:
* - the next method of an Observer
* - the handleEvent method of an EventListenerObject
* - the function itself, if it's a function
*/
const callable = (x) => x.next ? x.next.bind(x) :
x.handleEvent ? x.handleEvent.bind(x) :
x;
// FIXME: remove, use subscribe below instead
const asap = (fn, arg) => {
arg?.subscribe?.(fn) ??
arg?.then?.(fn.next?.bind(fn) ?? fn) ??
fn(arg);
};
/**
* Connect an event source to a sink through any compatible interface on any optionally specified scheduler
* @param node The node on which the binding is set
* @param source A Promise, Observable or EventEmitter
* @param next A "next" or "then" handler on the sink side
* @param error? An error handler on the sink side
* @param complete? a finalisation function
*/
const subscribe = (node, source, next, error, complete, scheduler) => {
// TODO: make this a plugin, in case people don't use handleEvent...
const flattenedNext = toListener(next);
const task = scheduler?.(node, flattenedNext) ?? flattenedNext;
if (isObservable(source)) {
// TODO: should we handle promise cancellations (cancellable promises?) too?
const subscription = source.subscribe({
next: task,
error,
complete,
});
subscriptions.get(node)?.push(subscription) ?? subscriptions.set(node, [subscription]);
return subscription;
}
else if (isPromise(source)) {
source.then(task, error).finally(complete);
}
else {
// TODO: should we handle function cancellations (removeEventListener) too?
task(source);
}
};
export { asap, callable, subscribe };
//# sourceMappingURL=drain.js.map