0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.