【问题标题】:Multiple RXJS BehaviorSubjects to trigger function call多个 RXJS BehaviorSubjects 触发函数调用
【发布时间】:2020-05-28 08:40:02
【问题描述】:

我想运行一个计算密集型函数,该函数依赖于 3 个 behaviorSubjects 的最新值。 有时所有科目同时更改,我不想运行 3 次计算。 这就是我现在实现它的方式。

this.subscription = merge(behaviorSubject1$, behaviorSubject2$, behaviorSubject3$)
        .pipe(throttleTime(300)) //this is to avoid running the function 3 times when all subjects change simultaneously
        .subscribe(() => {
           const answer = getSolution(subject1$.getValue(), subject2$.getValue(), subject3$.getValue());

        });

我不确定这是否是最好的方法。非常感谢任何帮助

【问题讨论】:

    标签: angular rxjs observable reactive-programming behaviorsubject


    【解决方案1】:

    看你想做什么

    您要根据最新值进行计算吗? 那么你的方法很好,但是使用 combineLatest 代替,任何发射都会导致计算。

    this.subscription = combineLatest(behaviorSubject1$, behaviorSubject2$, behaviorSubject3$)
            .pipe(throttleTime(300))
            .subscribe(([o1, o2, o3]) => {
              const answer = getSolution(o1, o2, o3);
            });
    

    您想逐一计算所有这些吗? 使用 concatMap。

    this.subscription = combineLatest(behaviorSubject1$, behaviorSubject2$, behaviorSubject3$).pipe(
      concatMap(([o1, o2, o3]) => getSolution(o1, o2, o3)), // getSolution should be an observable.
    )
            .subscribe(solution => {
            });
    

    您想在计算过程中忽略发射吗? 使用排气地图。

    this.subscription = combineLatest(behaviorSubject1$, behaviorSubject2$, behaviorSubject3$).pipe(
      exhaustMap(([o1, o2, o3]) => getSolution(o1, o2, o3)), // getSolution should be an observable.
    )
            .subscribe(solution => {
            });
    

    您想计算所有 3 项都已更改的时间吗? 使用 zip。

    this.subscription = zip(behaviorSubject1$, behaviorSubject2$, behaviorSubject3$)
            .subscribe(([o1, o2, o3]) => {
               const answer = getSolution(o1, o2, o3);
            });
    

    【讨论】:

      【解决方案2】:

      在这种情况下最好使用combineLatest() 而不是merge()

      this.subscription = combineLatest([behaviorSubject1$, behaviorSubject2$, behaviorSubject3$])
        .pipe(throttleTime(300))
        .subscribe(([value1, value2, value3]) => {
           const answer = getSolution(value1, value2, value3);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多