Signalを受け取って次に更新された値で解決するPromiseを返す関数
もっと簡単にいかんものか。特に effect を挟む関係上、Injector が必要なのがイケてなさすぎる。
code:ts
function waitForNextValue<T>(sig: Signal<T>, injector: Injector): Promise<T> {
let effectRef: EffectRef;
const p = new Promise<T>((resolve) => {
let init = false;
runInInjectionContext(injector, () => {
effectRef = effect(() => {
const value = sig();
if (!init) {
init = true;
} else {
resolve(value);
}
});
});
});
p.finally(() => effectRef.destroy());
return p;
}
一応、テスト専用のユーティリティとしてTestBedがあることを前提にすれば引数にInjectorは要らなくなるが、しかし...。
code:ts
function waitForNextValue<T>(sig: Signal<T>): Promise<T> {
let effectRef: EffectRef;
const p = new Promise<T>((resolve) => {
let init = false;
TestBed.runInInjectionContext(() => {
effectRef = effect(() => {
const value = sig();
if (!init) {
init = true;
} else {
resolve(value);
}
});
});
});
p.finally(() => effectRef.destroy());
return p;
}