#Flatten list of observables

3 messages · Page 1 of 1 (latest)

sly sandal
#

Hi,

I want to display a foldertree with folders that contain blueprints. Folders and blueprints are saved separately, so I need to get the blueprints of the folder with a different call. The db is observable based, so I (mis?)use switchmap to get the data.

I create an observable of each folder to get the corresponding blueprints from the database. I use forkjoin to get me the results and return the folders and blueprints as two arrays like: [ blueprintFolders: BlueprintFolder[], blueprints: Blueprint[] ].
The problem is that blueprints is now of type Blueprint[][] instead of Blueprint[], I just want a flat result of all blueprint calls merged in 1 'response'.
I tried mergeAll(), but that returns a result after every emit.

My fix feels kind of dirty by using flat(1) to flatten the Blueprint[][].

switchMap((blueprintFolders: BlueprintFolder[]) => {
          let blueprints$ = blueprintFolders.map(bpf => this.blueprintsService.getBlueprintsByBlueprintFolder(bpf.key));

          return forkJoin(blueprints$).pipe(
            map((blueprints)=> [blueprintFolders, blueprints]),
            catchError(err => of([], []))
          );
        }),
        map(([blueprintFolders, blueprints]: [BlueprintFolder[], Blueprint[]]) => this.blueprintFolderService.createBlueprintFolderViewModel(blueprintFolders, blueprints.flat(1))),
small dove
#

If you want the result of the switchMap call to return two arrays of objects, you could call reduce on the blueprints you return in map function like

        return forkJoin(blueprints$).pipe(
          map((blueprints) => [blueprintFolders, blueprints.reduce((bp, itm) => bp.concat(itm), [])]),
          catchError(err => of([], []))
        );
small dove
#

or something like this if you want to keep it as rx as possible


        return forkJoin(blueprints$).pipe(
          reduce((acc, val) => acc.concat(...val), []),
          map(val => [blueprintFolders, val]),
          catchError(err => of([], []))
        )