78 lines
1.9 KiB
TypeScript
78 lines
1.9 KiB
TypeScript
import Observable, { ObserverCallback } from "./observable";
|
|
|
|
export default class AwaitStore<T = any> {
|
|
private observable = new Observable<T>();
|
|
constructor(private _value: T) {
|
|
this.subscribe = this.subscribe.bind(this);
|
|
this.unsubscribe = this.unsubscribe.bind(this);
|
|
}
|
|
|
|
get value() {
|
|
return this._value;
|
|
}
|
|
|
|
send(value: T) {
|
|
this._value = value;
|
|
this.observable.send(value);
|
|
}
|
|
|
|
subscribe(handler: ObserverCallback<T>) {
|
|
handler(this._value);
|
|
this.observable.subscribe(handler);
|
|
return () => this.unsubscribe(handler);
|
|
}
|
|
|
|
unsubscribe(handler: ObserverCallback<T>) {
|
|
this.observable.unsubscribe(handler);
|
|
}
|
|
|
|
awaitValue(val: T): PromiseLike<void> & { catch: (cb: (err: any) => PromiseLike<void>) => PromiseLike<void>, ignore: () => void } {
|
|
|
|
let ignore: () => void;
|
|
|
|
let prms = new Promise<void>(yes => {
|
|
const cb = () => {
|
|
if (this._value === val) {
|
|
yes();
|
|
this.observable.unsubscribe(cb);
|
|
return true;
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
ignore = () => {
|
|
this.observable.unsubscribe(cb);
|
|
}
|
|
|
|
if (!cb()) {
|
|
this.observable.subscribe(cb);
|
|
}
|
|
});
|
|
|
|
return {
|
|
then: prms.then.bind(prms),
|
|
catch: prms.catch.bind(prms),
|
|
ignore: () => ignore()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates Public API with subscribe and unsubscribe
|
|
*
|
|
* @returns {object}
|
|
*/
|
|
getPublicApi() {
|
|
if (this.observable.closed)
|
|
throw new Error("Observable is closed!");
|
|
return {
|
|
subscribe: (callback: ObserverCallback<T>) => this.subscribe(callback),
|
|
unsubscribe: (callback: ObserverCallback<T>) => this.unsubscribe(callback),
|
|
awaitValue: (value: T) => this.awaitValue(value)
|
|
}
|
|
}
|
|
|
|
close() {
|
|
this.observable.close();
|
|
}
|
|
} |