RxJS 6/tap 运算符何时发出值

标签 rxjs ngrx rxjs5 rxjs6 ngrx-store

我一直想知道是否可以安全地假设在使用 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/

相关文章:

javascript - RxJs5 在没有运动时发出信号

javascript - 连接 : how to handle each subscribe with a specific next function as independent

rxjs - 使用 Subject.create 创建的主题无法取消订阅

angular - 路由解析器不适用于 Angular 中的嵌套 Observables

javascript - 当一次就足够时,RxJs 响应式(Reactive)映射被调用两次

node.js - 如何等待发货完成后再从商店挑选。 Ngrx相关问题

angular - 在 redux/ngrx 应用架构中初始化模型对象的位置

node.js - 如何链接以前在 forkjoin() 操作中的一组可观察量

angular - subscribe 不是尝试在 Angular 2 中使用 JSON 文件时抛出的函数错误

javascript - 避免 NgRxReducer 中的状态突变