【问题标题】:Compare most recent values from multiple BehaviorSubjects比较来自多个 BehaviorSubjects 的最新值
【发布时间】:2018-07-16 01:58:24
【问题描述】:

说我有这个:

  isMatchedCountLessThanTotalCountMessage(){
       // I want to implement this
       // "returns" a string asynchronously
  }

  getMatchedEventsCount() {
    return this.dcs.matchCount.asObservable();
  }

  getTotalEventsCount() {
    return this.dcs.totalCount.asObservable();
  }

matchedCount 和 totalCount 是这样的:

  public matchCount = new BehaviorSubject<number>(0);
  public totalCount = new BehaviorSubject<number>(0);

这些 Observable 会随着值的变化而触发整数。每当一个值被其中一个触发时,我想比较两者中的两个最新值,我该怎么做?

我想做的是从方法中返回一个布尔值

所以我可以在 HTML 中显示:

 <div>{{(isMatchedCountLessThanTotalCountMessage() | async)}}</div>

我认为 Observable.zip 可以解决问题:

isMatchedCountLessThanTotalCountMessage(){
    return Observable.zip(
      this.getMatchedEventsCount(),
      this.getTotalEventsCount()
    )
    .subscribe(function(v){
      const intA = v[0];
      const intB = v[1];

        if(intA > intB)
         // but I don't know how to send a message the HTML from here
    });
  }

【问题讨论】:

    标签: rxjs rxjs5 angular2-observables behaviorsubject


    【解决方案1】:

    这很有效,尽管我们可以使用 Observable.zip 以外的东西。

     isMatchedCountLessThanTotalCount() {
        return Observable.create(obs => {
          return Observable.zip(
            this.getMatchedEventsCount(),
            this.getTotalEventsCount()
          )
          .subscribe(v => {
            if ((v[1] - v[0]) > 0) {
              obs.next('(results ARE filtered)')
            }
            else {
              obs.next('(results are not filtered)');
            }
          });
        });
      }
    

    实际上有一种更简单的方法可以使用所谓的“投影函数”:

      isMatchedCountLessThanTotalCount() {
        return Observable.combineLatest(
          this.getMatchedEventsCount(),
          this.getTotalEventsCount(),
          function (one, two) {
            if ((two - one) > 0) {
              return '(results ARE filtered)'
            }
            return '(results are not filtered)';
          }
        )
      }
    

    Observable.combineLatest() 类似于Observable.zip(),但会触发第一个新值,它不会等待来自所有可观察对象的新值。

    【讨论】:

      【解决方案2】:

      您可以轻松使用.map() 函数来转换您想要的数据:

      isMatchedCountLessThanTotalCountMessage() {
          return Observable.combineLatest(
              this.getMatchedEventsCount(),
              this.getTotalEventsCount(),
          )
              .map(([intA, intB]) => {
                  return intA > intB ? '(results ARE filtered)' : '(results are not filtered)'
              })
      }
      

      【讨论】:

      • @AlexanderMills 你真的应该只在它起作用/解决你的问题后才接受答案
      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2020-11-21
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多