blob: a9e23e8c7cd531d7574724f40fcd30269dda10cd (
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
|
/*
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;
}
wait_for(val: T) {
return new Promise<void>(r => {
const abort = this.onchangeinit(v => {
if (v == val) {
r()
abort()
}
})
})
}
}
|