aboutsummaryrefslogtreecommitdiff
path: root/src/observable.ts
blob: bd669638de35338c5d9b52181f7bd2ea89d66b4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
    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) 2024 metamuffin <metamuffin.org>
*/
export class OVar<T> {
    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<U>(fn: (v: T) => U): OVar<U> {
        const uv = new OVar(fn(this.value))
        uv.cancel_source = this.onchange(v => uv.value = fn(v))
        uv.weak = true
        return uv;
    }
    liftA2<U, V>(other: OVar<U>, fn: (x: T, y: U) => V): OVar<V> {
        const uv = new OVar(fn(this.value, other.value))
        uv.cancel_source = this.onchange(x => uv.value = fn(x, other.value))
        uv.cancel_source = other.onchange(y => uv.value = fn(this.value, y))
        uv.weak = true
        return uv;
    }
    wait_for(val: T) {
        return new Promise<void>(r => {
            const abort = this.onchangeinit(v => {
                if (v == val) {
                    r()
                    abort()
                }
            })
        })
    }
}