@mittwald/react-use-promise
Version:
Simple and declarative use of Promises in your React components. Observe their state and refresh them in various advanced ways.
26 lines (25 loc) • 673 B
JavaScript
export class ObservableValue {
value;
// using unknown since otherwise the ObservableValue seems to be invariant on type T
observers = new Set();
constructor(value) {
this.value = value;
}
notifyObservers(newValue) {
this.observers.forEach((o) => o(newValue));
}
get observerCount() {
return this.observers.size;
}
observe(observer) {
this.observers.add(observer);
return () => this.observers.delete(observer);
}
updateValue(newValue) {
if (this.value === newValue) {
return;
}
this.value = newValue;
this.notifyObservers(newValue);
}
}