-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal.ts
58 lines (43 loc) · 1.13 KB
/
signal.ts
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
// Signal.ts
type Listener<T> = (data: T) => void;
class Signal<T> {
private listeners: Listener<T>[] = [];
private value: T;
constructor(initialValue: T) {
this.value = initialValue;
}
subscribe(listener: Listener<T>): () => void {
this.listeners.push(listener);
// Return a function to unsubscribe
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
getValue(): T {
return this.value;
}
setValue(newValue: T): void {
this.value = newValue;
this.notify();
}
private notify(): void {
this.listeners.forEach((listener) => {
listener(this.value);
});
}
}
// Example usage:
// Define a type for the signal data
type CounterSignalData = number;
// Create an instance of Signal
const counterSignal = new Signal<CounterSignalData>(0);
// Subscribe to the signal
const unsubscribe = counterSignal.subscribe((count) => {
console.log(`Count: ${count}`);
});
// Get initial value
console.log(`Initial Count: ${counterSignal.getValue()}`);
// Update the signal value
counterSignal.setValue(1);
// Unsubscribe (stop listening)
unsubscribe();