RxJs - forkJoin with empty array

Additionally to martin's answer.

I had 2 observables returning arrays and if one of them gives me an empty array, it did not wait for the other observable to finish and completed instantly. You can handle such cases as follows using defaultIfEmpty.

const response1: Observable<any[]> = this.service.getResponse(params1).pipe(defaultIfEmpty([]));
const response2: Observable<any[]> = this.service.getResponse(params2).pipe(defaultIfEmpty([]));

Observable.forkJoin(response1, response2).subscribe((response) => {
  console.log(response);
}, () => {
  console.log('handle error here');
}, () => {
  console.log('completed');
});

That's because forkJoin requires all source Observables to emit at least one item and when there are no source Observables there's nothing to emit. However, forkJoin will still send the complete notification so you can use for example defaultIfEmpty operator to make sure it always emits at least one next.

forkJoin(observables).pipe(
  defaultIfEmpty(null),
).subscribe(...);

Demo: https://stackblitz.com/edit/rxjs-kkd1qa?file=index.ts

Tags:

Rxjs