首页 > 解决方案 > 在数组流上使用 RxJS 过滤器操作符

问题描述

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

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 运算符

标签: angulartypescriptrxjsreactivex

解决方案


你可以试试这样的

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

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


推荐阅读