jsketcher/modules/lstream/combine.js
2018-06-22 00:31:33 -07:00

38 lines
No EOL
822 B
JavaScript

import {StreamBase} from './base';
export class CombineStream extends StreamBase {
constructor(streams) {
super();
this.streams = streams;
this.values = this.streams.map(() => NOT_INITIALIZED);
this.ready = false;
}
attach(observer) {
let detachers = new Array(this.streams.length);
this.streams.forEach((s, i) => {
detachers[i] = s.attach(value => {
this.values[i] = value;
if (!this.ready) {
this.ready = this.isReady();
}
if (this.ready) {
observer(this.values);
}
});
});
return () => detachers.forEach(d => d());
}
isReady() {
for (let val of this.values) {
if (val === NOT_INITIALIZED) {
return false;
}
}
return true;
}
}
const NOT_INITIALIZED = {};