我一直想知道是否可以安全地假设在使用 Tap 运算符后,其内部的副作用已经完成。
我的用例是 ngrx。
...
tap(() => {
this.store.dispatch(new SetValue("Hello World"));
}
}),
switchMap(() => this.store),
select(state => state.value),
tap(state => {
if (state === undefined) {
throw new Error("Couldn't find value");
}
})
SetValue是一个实现ngrx的类
export class SetValue implements Action {
readonly type = SET_VALUE;
constructor(public payload: string) {}
}
我想要实现的是在商店中设置一个值,然后检查它是否已有效设置。
我可以假设在点击运算符(operator)后调度已完成吗?
回答
我在Angular Router Guards上使用它来通过网址上的参数设置初始状态,因此我最终过滤为仅在商店有新值时才继续
...
tap(() => this.store.dispatch(new SetValue("Hello World"))),
switchMap(() => this.store),
select(state => state.value),
filter(value => value === "Hello World"),
take(1)
最佳答案
RxJS 中的大多数操作都是同步的,因此如果 this.store.dispatch(new SetValue("Hello World"))
不会执行任何异步任务,它可能会按预期工作(它仍然只是幕后的主题)。
但是,您不应该依赖此行为。 NgRx 可能会改变它的内部结构,一般来说,最好不要依赖 RxJS 运算符的同步/异步(这在过去已经发生过,例如从 RxJS 4 到 RxJS 5 的 from()
)。
如果您想确保某些内容已设置,请更改您的 new SetValue("Hello World")
效果,以便在完成需要执行的操作后发出另一个操作。
关于RxJS 6/tap 运算符何时发出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282811/