export type ObserverCallback = (data: T[]) => void; export default class Observable { private subscriber: { callback: ObserverCallback, one: boolean }[] = []; private events: T[] = []; private timeout = undefined; constructor(private collect: boolean = true, private collect_intervall: number = 100) { } getPublicApi() { return { subscribe: (callback: ObserverCallback, one: boolean = false) => { let oldcb = this.subscriber.find(e => e.callback === callback); if (oldcb) oldcb.one = one else this.subscriber.push({ callback, one }) }, unsubscribe: (callback: ObserverCallback) => { let idx = this.subscriber.findIndex(e => e.callback === callback); if (idx >= 0) { this.subscriber.splice(idx, 1); } } } } send(data: T) { if (!this.collect) this.subscriber.forEach(e => e.callback([data])); else { this.events.push(data); if (!this.timeout) { this.timeout = setTimeout(() => { this.subscriber.forEach(cb => { if (cb.one) this.events.forEach(e => cb.callback([e])); else cb.callback(this.events) }); this.timeout = 0; }, this.collect_intervall); } } } }