我仍然可以依赖 pipe(take(1)).subscribe() 来同步 运行 吗?
Can I still rely on pipe(take(1)).subscribe() to run synchronously?
我正在尝试同步获取 observable 的最新状态。根据 this migration document for ngrx/store 2.0 you can always rely on subscribe() running synchronously if you have to get the state value
.
我找不到任何支持此的当前文档。这是否仍然适用于商店的当前版本(例如 7.4.0)?
示例代码:
method(someId: string): string {
let value: string;
this.service.getSomeValue$(someId).pipe(take(1)).subscribe(s => value = s);
return value;
}
Observable 将始终具有最新的状态(除非构建为其他方式)。
同步意味着您不使用回调。
话虽如此,您可以简单地使用
async myFunc() {
lastValue = await myObs$.fromPromise();
}
这将以同步方式 return 观察到的最后一个值。
试试这个:
method(someId: string): string {
let value: string;
this.service.getSomeValue$(someId).pipe(take(1)).subscribe(s =>
value = s;
return value;});
}
如果你想知道一些代码是否同步运行而不深入源代码,你可以测试它。
设置一些异步代码(如setTimeout
或Promise
(首先在宏队列上运行,其次在微队列上运行)),然后是您要测试的代码,然后是一些同步代码。结果应该是:
- 您测试的代码
- 同步代码
- 异步代码
如果结果是那样,你的代码是同步的。
我正在尝试同步获取 observable 的最新状态。根据 this migration document for ngrx/store 2.0 you can always rely on subscribe() running synchronously if you have to get the state value
.
我找不到任何支持此的当前文档。这是否仍然适用于商店的当前版本(例如 7.4.0)?
示例代码:
method(someId: string): string {
let value: string;
this.service.getSomeValue$(someId).pipe(take(1)).subscribe(s => value = s);
return value;
}
Observable 将始终具有最新的状态(除非构建为其他方式)。
同步意味着您不使用回调。
话虽如此,您可以简单地使用
async myFunc() {
lastValue = await myObs$.fromPromise();
}
这将以同步方式 return 观察到的最后一个值。
试试这个:
method(someId: string): string {
let value: string;
this.service.getSomeValue$(someId).pipe(take(1)).subscribe(s =>
value = s;
return value;});
}
如果你想知道一些代码是否同步运行而不深入源代码,你可以测试它。
设置一些异步代码(如setTimeout
或Promise
(首先在宏队列上运行,其次在微队列上运行)),然后是您要测试的代码,然后是一些同步代码。结果应该是:
- 您测试的代码
- 同步代码
- 异步代码
如果结果是那样,你的代码是同步的。