【问题标题】:Rxjs Combine multiple observables to a single boolean observableRxjs 将多个 observable 组合成一个 boolean observable
【发布时间】:2021-06-04 19:55:33
【问题描述】:

我正在尝试将多个可观察对象组合成一个布尔可观察对象。

目前我正在使用扫描,当我需要它每次都使用 true 时,它​​正在使用之前为累加器发出的值运行。我不确定如何实现这一点。

    this.partnershipFundInvalid$ = merge(
      this.partnershipFundId$.pipe(map(id => id === null)),
      this.partnershipsFileUploader.dataImportState$.pipe(map(state => state.file !== null)),
    ).pipe(
      scan((acc, val) => {
        return acc && val === true;
      }, true),
    );

【问题讨论】:

  • 听起来你不需要scan。你能用map(val => val === true)吗?
  • @SteveHolgado 地图在所有流关闭之前不会发出
  • 您正在使用merge,因此通过map 的管道应在每次排放时运行...
  • 您需要 takeLast(10) 才能按照您描述的方式使用地图。你没有帮助
  • 这个问题显然需要更多关于预期输出和实际输出的细节,所以投票结束。

标签: angular rxjs


【解决方案1】:

扫描,但忽略累计值

    this.partnershipFundInvalid$ = merge(
      this.partnershipFundId$.pipe(map(id => id === null)),
      this.partnershipsFileUploader.dataImportState$.pipe(map(state => state.file !== null)),
    ).pipe(
      scan((acc, val) => {
        return true && val === true; // Replaced acc with "true"
      }, true),
    );

这在语义上与 map 相同

    this.partnershipFundInvalid$ = merge(
      this.partnershipFundId$.pipe(map(id => id === null)),
      this.partnershipsFileUploader.dataImportState$.pipe(map(state => state.file !== null)),
    ).pipe(
      map(val => {
        return true && val === true;
      }),
    );

在所有流都关闭之前,map 不会发出

这不是 map 的工作方式,它不处理错误或完成排放。


我建议更新您的问题以包含您想要完成的内容,因为 '我正在尝试“减少”布尔值' 是模棱两可的。有很多方法可以“减少”布尔值

【讨论】:

  • 谢谢,但它只会使用合并中的最后一个 observable,像求和布尔值一样考虑它
【解决方案2】:

朋友建议的,我完全想多了。

this.partnershipFundInvalid$ = combineLatest(
  this.partnershipFundId$,
  this.partnershipsFileUploader.dataImportState$,
).pipe(
  map(([fundId, partnershipsFile]) => {
    return fundId == null && partnershipsFile.file !== null;
  }),
);

【讨论】:

  • 为什么不使用 switchMap 时使用它?使用 CombineLatest + 地图。代码将更具可读性并且会更少。
  • 如果我这样做我会得到一个错误TS2322: Type 'Observable<Observable<boolean>>' is not assignable to type 'Observable<boolean>'.   Type 'Observable<boolean>' is not assignable to type 'boolean'.我需要返回一个新的 observable
  • 不要使用“of”运算符,直接返回fundId == null && partnersFile.file !== null
  • 我什至没有注意到我里面有'of' ??‍♂️谢谢队友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2020-06-19
  • 2019-12-25
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多