cyclejs-stream
Version:
Observable (events stream) to which you can inject another streams.
82 lines (63 loc) • 2.44 kB
JavaScript
import 'core-js/fn/object/entries';
import { Rx } from '@cycle/core';
function _throwThatNotObservable() {
throw new TypeError('source must be an observable or interactions object!');
}
export default class InputProxy extends Rx.Subject {
constructor() {
super();
this.type = 'InputProxy';
this._interactions = {};
this._wasPassed = false;
this._subscriptions = new Rx.CompositeDisposable();
}
dispose() {
super.dispose();
this._subscriptions.dispose();
}
// multistream like interactions
get(selector, eventName) {
if (!this._interactions.hasOwnProperty(selector)) {
this._interactions[selector] = {};
}
if (!this._interactions[selector].hasOwnProperty(eventName)) {
this._interactions[selector][eventName] = new Rx.Subject();
}
return this._interactions[selector][eventName];
}
pass(source) {
if(arguments.length > 1) {
throw new Error('only one source can be passed');
}
if(this._wasPassed) {
throw new Error('source already passed');
}
if(('undefined' === typeof source) || (source === null)) {
_throwThatNotObservable();
// multistream (interactions object)
} else if('function' === typeof source.get) {
for(let [ selector, events ] of Object.entries(this._interactions)) {
for(let [ eventName, proxyEvent$ ] of Object.entries(events)) {
let sourceEvent$ = source.get(selector, eventName);
if(sourceEvent$ && (sourceEvent$.subscribe instanceof Rx.Observable)) {
let subscription = sourceEvent$.subscribe(proxyEvent$.asObserver());
this._subscriptions.add(subscription);
} else {
_throwThatNotObservable();
}
}
}
// single stream
} else if(source instanceof Rx.Observable) {
let subscription = source.subscribe(this.asObserver());
this._subscriptions.add(subscription);
} else {
_throwThatNotObservable();
}
this._wasPassed = true;
return this._subscriptions;
}
get wasPassed() {
return this._wasPassed;
}
}