Use RxJS filter operators on stream of arrays

XRaycat

I was wondering if it's possible to operate, e.g. filtering, on a stream of arrays and then emit the arrays again without concatenating the elements of the arrays or using regular array operators. Let's say that I have an observable containing a single array. Then I can do the following:

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();

What if sub.complete() is not called and there are multiple emissions of fruit[] (e.g. fruitBasket2). Can the observable emit two arrays ([orange, orange], [orange]) without using regular array operators? It's easy to do with map(RxJS) -> filter(array operator), but I will like to know if it's possible only using RxJS operators

Picci

You can try something like this

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

The key idea is that you transform each array emitted by the source in a stream via the from operator and then, on this single stream related to a single array, you apply the rxjs filter and toArray logic.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related