在数组流上使用 RxJS 过滤器运算符
Use RxJS filter operators on stream of arrays
我想知道是否可以操作,例如对数组流进行过滤,然后在不连接数组元素或使用常规数组运算符的情况下再次发出数组。假设我有一个包含单个数组的可观察对象。然后我可以执行以下操作:
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 operators
你可以试试这个
sub
.asObservable()
.pipe(
concatMap(x =>
from(x).pipe(
filter(x => x.weight > MINWEIGHT),
toArray()
)
)
)
.subscribe(console.log);
关键思想是通过 from
运算符转换流中源发出的每个数组,然后,在与单个数组相关的单个流上,应用 rxjs filter
和 toArray
逻辑。
我想知道是否可以操作,例如对数组流进行过滤,然后在不连接数组元素或使用常规数组运算符的情况下再次发出数组。假设我有一个包含单个数组的可观察对象。然后我可以执行以下操作:
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 operators
你可以试试这个
sub
.asObservable()
.pipe(
concatMap(x =>
from(x).pipe(
filter(x => x.weight > MINWEIGHT),
toArray()
)
)
)
.subscribe(console.log);
关键思想是通过 from
运算符转换流中源发出的每个数组,然后,在与单个数组相关的单个流上,应用 rxjs filter
和 toArray
逻辑。