【问题标题】:How to merge 2 Observables and emit values based on specific conditions in Angular 8?如何合并 2 个 Observables 并根据 Angular 8 中的特定条件发出值?
【发布时间】:2020-12-16 18:29:25
【问题描述】:

我有 2 个observables

const obsA = this.api.ObsA();
const obsB = this.api.ObsB();

并且我想将join 他们转换成single observable,这将使EMIT 值仅遵循某些规则:

  • -如果发射,它必须emit both values,最好是array,第一个值:arr[0],第二个值:arr[1]
  • -如果obsA 发出NULL,那么我必须运行:subjectObsB.next(null),同时将obsB 的值设置为NULL,并同时发出null 值。
  • -如果 2 个 observable 中的任何一个发出 new value,则立即将其与另一个 Observable's 最新发出的值一起发出。 (当然 首先应用上述规则)

我最好的选择是什么?

我尝试遵循这条路线:

const mergedObs = merge(
      this.obsA().pipe(
        tap((s) => {
          if (s == null) this.api.resetObsB(null);
        })
      ),
      this.obsB()
    );

但它不起作用,我想我在这里遗漏了一些逻辑

【问题讨论】:

    标签: angular observable


    【解决方案1】:

    您可以使用combineLatest 合并两个可观察对象:https://rxjs-dev.firebaseapp.com/api/index/function/combineLatest(请注意,文档将每个可观察对象显示为自己的参数,但它们必须作为数组传递)

    combineLatest([obs1, obs2]).pipe(map(([val1, val2]) => {
      // not sure if this is the best solution, may trigger a subscriber twice
      if (val1 === null) {
        obs2.next(null);
        return [null, null];
      }
      return [val1, val2];
    }).subscribe(([val1, val2]) => {
    
    });
    

    或领取您的代码

    const mergedObs = combineLatest(
      this.obsA().pipe(
        tap((s) => { if (s == null) this.api.resetObsB(null);})
      )),
      this.obsB()
    );
    
    mergedObs.subscribe(([latestValueFromObsA, latestValueFromObsB]) => {
      // do stuff
    });
    

    【讨论】:

    • 注意,这个合并后的 Observable 将与其他 observable 一起进入 combineLatest,所以如果我按照这种方法,基本上我会有一个嵌套的 combineLatest,可以吗?
    • @AJ989 也用你的示例代码更新了我的 awnser
    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    相关资源
    最近更新 更多