【问题标题】:Use RxJS filter operators on stream of arrays在数组流上使用 RxJS 过滤器操作符
【发布时间】:2021-03-06 08:06:47
【问题描述】:

我想知道是否可以操作,例如在数组流上过滤,然后再次发出数组,而不连接数组的元素或使用常规数组运算符。假设我有一个包含单个数组的可观察对象。然后我可以执行以下操作:

const MINWEIGHT = 15;

interface fruit {
  name: string;
  weight: number;
}

let apple: fruit = { name: "apple", weight: 2 };
let orange: fruit = { name: "orange", weight: 20 };

let fruitBasket1 = [apple, orange, orange];
let fruitBasket2 = [apple, apple, apple];

let sub = new Subject<fruit[]>();

sub
  .asObservable()
  .pipe(
    concatMap(x => x),
    filter(x => x.weight > MINWEIGHT),
    toArray()
  )
  .subscribe(console.log); // result: [ orange, orange];

sub.next(fruitBasket1);
sub.complete();

如果sub.complete() 没有被调用并且有多个fruit[] (e.g. fruitBasket2) 的发射怎么办。 observable 可以在不使用常规数组运算符的情况下发出两个数组([orange, orange], [orange]) 吗?使用 map(RxJS) -> filter(array operator) 很容易,但我想知道是否可以仅使用 RxJS 运算符

【问题讨论】:

    标签: angular typescript rxjs reactivex


    【解决方案1】:

    你可以试试这样的

    sub
      .asObservable()
      .pipe(
        concatMap(x =>
          from(x).pipe(
            filter(x => x.weight > MINWEIGHT),
            toArray()
          )
        )
      )
      .subscribe(console.log);
    

    关键思想是通过from 运算符将源发出的每个数组转换为流中的每个数组,然后在与单个数组相关的单个流上应用rxjs filtertoArray 逻辑.

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 2016-10-25
      • 2018-06-16
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多