@thi.ng/rstream
Version:
Reactive streams & subscription primitives for constructing dataflow graphs / pipelines
82 lines (81 loc) • 1.79 kB
JavaScript
import {
State
} from "./api.js";
import { isFirstOrLastInput } from "./checks.js";
import { __optsWithID } from "./idgen.js";
import { __removeAllIDs } from "./internal/remove.js";
import { Subscription } from "./subscription.js";
const merge = (opts) => new StreamMerge(opts);
class StreamMerge extends Subscription {
sources;
constructor(opts) {
opts = opts || {};
super(void 0, __optsWithID("streammerge", opts));
this.sources = /* @__PURE__ */ new Map();
opts.src && this.addAll(opts.src);
}
add(src) {
this.ensureState();
this.sources.set(
src,
src.subscribe(
{
next: (x) => x instanceof Subscription ? this.add(x) : this.next(x),
done: () => this.markDone(src),
__owner: this
},
{ id: `in-${src.id}` }
)
);
}
addAll(src) {
for (const s of src) {
this.add(s);
}
}
remove(src) {
const sub = this.sources.get(src);
if (sub) {
this.sources.delete(src);
sub.unsubscribe();
return true;
}
return false;
}
removeID(id) {
for (const s of this.sources) {
if (s[0].id === id) {
return this.remove(s[0]);
}
}
return false;
}
removeAll(src) {
let ok = true;
for (const s of src) {
ok = this.remove(s) && ok;
}
return ok;
}
removeAllIDs(ids) {
return __removeAllIDs(this, ids);
}
unsubscribe(sub) {
if (!sub) {
for (const s of this.sources.values()) {
s.unsubscribe();
}
this.state = State.DONE;
this.sources.clear();
}
return super.unsubscribe(sub);
}
markDone(src) {
this.remove(src);
isFirstOrLastInput(this.closeIn, this.sources.size) && this.done();
}
}
export {
StreamMerge,
merge
};