/* This file is part of jshelper (https://codeberg.org/metamuffin/jshelper) which is licensed under the GNU Affero General Public License (version 3); see /COPYING. Copyright (C) 2023 metamuffin */ export class OVar { private _value: T private weak = false; // if weak, the source will be unsubscribed from, if all listeners are removed private disabled = false private cancel_source?: () => void private observers: ((v: T) => unknown)[] = [] constructor(initial: T) { this._value = initial; } get value() { return this._value } set value(v: T) { this._value = v; this.change() } change() { this.observers.forEach(o => o(this._value)) } onchange(handler: (v: T) => unknown): () => void { if (this.disabled) throw new Error("obervable is disabled"); this.observers.push(handler) if (this.observers.length > 16) console.warn("likely memory leak here:", this); return () => { this.observers = this.observers.filter(o => o != handler) if (this.observers.length == 0 && this.weak) { this.cancel_source!() this.disabled = true } } } onchangeinit(handler: (v: T) => unknown): () => void { const abort = this.onchange(handler) handler(this.value) return abort } map(fn: (v: T) => U): OVar { const uv = new OVar(fn(this.value)) uv.cancel_source = this.onchange(v => uv.value = fn(v)) uv.weak = true return uv; } wait_for(val: T) { return new Promise(r => { const abort = this.onchangeinit(v => { if (v == val) { r() abort() } }) }) } }