1

I have an array of data which describes entity relationships. My code:

services
            .tree
            .collection
            .find()
            .$
            .pipe(
                switchMap(from),
                groupBy((value) => value.get('parent_id')),
                mergeScan((memo, group$) => {
                    const key = group$.key;

                    return group$.pipe(
                        map((value) => {
                            if(!(key in memo)) {
                                memo[key] = [];
                            }
                            memo[key].push(value);

                            return memo;
                        })
                    )
                }, {}),
            )
            .subscribe((data) => console.log('data', data));

But instead of one log a have many. How can I merge all it in one pipeline to have a single data at the end?

Illorian
  • 1,222
  • 2
  • 13
  • 38
  • It is very unclear what you are trying to accomplish. I would suggest you set up a [codepen](https://codepen.io/) and demonstrate clearly what output you are expecting, and what output you are getting. – dmcgrandle Aug 22 '19 at 17:59
  • @dmcgrandle https://codesandbox.io/embed/rxjs-ass-s4354 The result I need is last in a console. I know that I can use `toArray()` and if I set it into this example everything works fine. But if I set it in my code I have no result at all( And I can't find right solution – Illorian Aug 23 '19 at 06:15

1 Answers1

1

I think two things are going on here in the CodeSandbox (I can't speak to what is happening directly in your editor on your desktop since I can't see what you are seeing).

  1. console.log(object) doesn't show you object's value when it was logged, but rather it displays a triangle, which is effectively a POINTER to that Object that isn't actually evaluated until you click it, by which time is has been completely filled in. To make console.log give you the value when it was logged (ie: a snapshot in time), just change the statement to: console.log("data", JSON.stringify(data)). More on that in this question and its answers.
  2. If you make that change you will start to see what is really going on, that it is slowly building what you are looking for and isn't actually complete until the last emission, ie: when it completes. This also clearly shows that the solution to your problem is to add the operator last() after your mergeScan().

Complete code from the CodeSandbox:

of(incoming)
  .pipe(
    switchMap(from),
    groupBy(value => value.parent_id),
    mergeScan((memo, group$) => {
      const key = group$.key;

      return group$.pipe(
        map(value => {
          if (!(key in memo)) {
            memo[key] = [];
          }
          memo[key].push(value);

          return memo;
        })
      );
    }, {}),
    last()
  )
  .subscribe(data => console.log("data", JSON.stringify(data, null, 2)));
dmcgrandle
  • 5,934
  • 1
  • 19
  • 38