RxJS BehaviourSubject 订阅时没有初始值

mot*_*son 11 rxjs angular

我有一个 Angular 应用程序,我在其中使用 RxJS BehaviourSubject 订阅指示“进行中”状态的 bool 值。

但我只对状态何时发生变化感兴趣,而不对订阅的当前状态感兴趣。

export class ProgressService {
  private InProgress$ = new BehaviorSubject<boolean>(false);

  constructor() {}

  public getInProgressStateSubject() {
    return this.InProgress$;
  }
}

...

this.progressService.getInProgressSubject().subscribe((inProgress: boolean) => {

  // This will be triggered in the moment of subscription as well as on state chages

  if (inProgress) {
    // Toggle on state
  } else {
    // Toggle off state
  }
});
Run Code Online (Sandbox Code Playgroud)

我喜欢它的工作方式,我只是不希望它在订阅时触发。

RxJS 中是否还有其他类似的运算符可以帮助我,或者我可以通过其他方式实现吗?

谢谢!

Mox*_*arm 7

我认为有几种选择:

  • 使用Subject
  • 保留BehaviorSubject,但使用 with 管道skip(1)忽略第一个值

  • Skip(1) 并不总是一个好的选择,因为如果您在另一个服务已发布有效值后订阅BehaviourSubject,则可能会无意中跳过有效值。 (3认同)