LaMut
LaMut

Reputation: 79

What's the best way to merge consecutive Observables' results?

Let's say I have an Observable which results in an Object of 3 arrays like this :

    results = {
        type1: [...],
        type2: [...],
        type3: [...],
    };

Is there a rxjs operator which allows me to combine multiple observables and their results in order to have a final result like this :

    results1 = {
        type1: [1, 2],
        type2: ['ab', 'cd'],
        type3: ['foo', 'bar'],
    };

    results2 = {
        type1: [3, 4, 5],
        type2: ['ef', 'gh', 'ij'],
        type3: ['ban', 'jo', 'vi'],
    };

    final_results = {
        type1: [1, 2, 3, 4, 5],
        type2: ['ab', 'cd', 'ef', 'gh', 'ij'],
        type3: ['foo', 'bar', 'ban', 'jo', 'vi'],
    };

?????

For the record I'm using Angular 2+ and typescript, and I want to keep using Observable streams and rxjs operators, but according to their documentation I'm not sure they're one which could do something like 'deep merging ??'

Thanks for helping

Upvotes: 2

Views: 1168

Answers (3)

Davy
Davy

Reputation: 6441

You are looking for the scan operator:

https://www.learnrxjs.io/operators/transformation/scan.html

It is similar to the reduce operator, but the reduce operator will only emit at the end of the stream. The scan operator will emit the intermediate value every time.

Upvotes: 3

A.Winnen
A.Winnen

Reputation: 1698

you can use the reduce operator to aggregate a single result from many emitted values. It's up to you to merge the single arrays since this is not related to rxjs

Simple example: https://stackblitz.com/edit/angular-cffyyh

Upvotes: 1

user4676340
user4676340

Reputation:

This isn't observable-related, this is plain old Javascript.

The only operator you have to know is combineLatest :

combineLatest(results1$, results2$).pipe(
  map((results1, results2) => {
    const ret = {};
    Object.keys(results1).foreEach(key => ret[key] = results1[key].concat(results2[key]));
    return ret;
  })
).subscribe(res => console.log(res)); // should display your expected result

Don't be mistaken : RxJS operators manipulate the stream (the Observable itself), not the data in it.

If you want to handle the internal data, this becomes Javascript.

Upvotes: 1

Related Questions