Which rxjs operator to use to query many tables but the result exists in only one of the tables

36 Views Asked by At

We have five different tables, but the user exists only in one of them, we don't know which one it is, which operator is best to use to query all of them at the same time? I'm using

forkJoin([getUserTable1$, getUserTable2$, ..]).subscribe((res) => console.log(res))

But four of them throw error and the resulting forkJoin result is also in error Which rxjs operator is best to use in this case? I've tried to pipe each observable with error handling but doesn't work

getUserTable1$.pipe(catchError(() => { return EMPTY; })) etc

Of course i can query each table separately but I want to use only one subscription

1

There are 1 best solutions below

1
user776686 On

The problem is in returning EMPTY

As the docs say, the resulting stream is:

Observable emitting either an array of last values emitted by passed Observables or value from project function.

Mind these words: of last values emitted -> EMPTY does not emit anything.

The below code works for me on stackblitz:

import { of, map, defer, throwError, forkJoin, EMPTY, catchError } from 'rxjs';

const src1$ = defer(() => {
  console.log('1 subscribed');
  return of('found value');
}).pipe(catchError(() => of(undefined)));

const src2$ = defer(() => {
  console.log('2 subscribed');
  return throwError(() => new Error('err2'))
}).pipe(catchError(() => of(undefined)));


const src3$ = defer(() => {
  console.log('3 subscribed');
  return throwError(() => new Error('err3'));
}).pipe(catchError(() => of(undefined)));

const src4$ = defer(() => {
  console.log('4 subscribed');
  return throwError(() => new Error('err4'));
}).pipe(catchError(() => of(undefined)));

const search$ = forkJoin([
  src1$,
  src2$,
  src3$,
  src4$,
]);

search$.pipe(
  map(values => values.filter(Boolean)),
  map(([found]) => found),
).subscribe({
  next: val => console.log(val),
  error: err => console.log('error:', err) // should never print, errors suppressed with undefined values
});